<?php

namespace app\admin\controller;

use app\admin\service\GroupReportExportService;
use app\admin\service\ReportExportService;
use app\model\MessageModel;
use app\model\RatingScalePackModel;
use app\model\SelfFactorScoreModel;
use app\model\UnitModel;
use app\model\UserModel;
use app\user\service\RatingScaleService as UserRatingScaleService;
use app\admin\service\RatingScaleService;
use app\admin\service\ReportService;
use app\admin\service\TaskService;
use app\admin\service\UserService;
use app\BaseController;
use app\model\ConfigModel;
use app\model\DepartmentAdminModel;
use app\model\InterpretationRecordModel;
use app\model\ProxyEvaluationResultModel;
use app\model\RatingScaleFactorModel;
use app\model\RatingScalePackInfoModel;
use app\model\RatingScaleTypeModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskContinuousEvaluationModel;
use app\model\TaskModel;
use app\model\TaskRatingScaleModel;
use app\model\RatingScaleModel;
use app\model\TaskUserModel;
use app\model\TaskUserResultContinuityModel;
use app\model\TaskUserResultModel;
use app\model\WarningReportRecordModel;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\OssClient;
use Swoole\Coroutine\Channel;
use Swoole\Coroutine\WaitGroup;
use think\App;
use app\model\DepartmentModel;
use app\model\not_del\DepartmentModel as NotDelDepartmentModel;
use think\facade\Log;
use ZipArchive;
use app\model\not_del\RatingScaleModel as NotDelRatingScaleModel;
use app\model\not_del\UserModel as NotDelUserModel;
use app\model\not_del\DepartmentAdminModel as NotDepartmentAdminModel;

class Task extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new TaskModel();
    }

    /**
     * 自我团体
     * @return bool|string
     */
    public function selfGroup(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'unit_id|unit_id' => 'require',
            ]);
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $RatingScaleModel = new RatingScaleModel();
            $SelfFactorScoreModel = new SelfFactorScoreModel();
            $ids = $SelfEvaluationResultModel->where([
                ['unit_id','=',$param['unit_id']],
                ['rating_scale_id','=',$param['rating_scale_id']]
            ])->column('id');

            $ratingScaleInfo = $RatingScaleModel->field('id,name,mode_id')->with([
                'factor'
            ])->find($param['rating_scale_id']);
            if (!$ratingScaleInfo) throw new \Exception('参数错误！');
            $ratingScaleInfo = $ratingScaleInfo->toArray();
            $ratingScaleInfo['num'] = count($ids);
            foreach ($ratingScaleInfo['factor'] as $key => &$item) {
                if ($item['mode_id'] != $ratingScaleInfo['mode_id']) {
                    unset($ratingScaleInfo['factor'][$key]);
                    continue;
                }
                $item['warning'] = $SelfFactorScoreModel->where([
                    ['result_id','in',$ids],
                    ['factor_id','=',$item['id']],
                    ['is_warning','=',1]
                ])->count('id');
                $item['normal'] = $ratingScaleInfo['num'] - $item['warning'];

                $scoreArr = $SelfFactorScoreModel->where([
                    ['result_id','in',$ids],
                    ['factor_id','=',$item['id']]
                ])->column('score');
                $item['max_score'] = max($scoreArr);
                $total = array_sum($scoreArr);
                $count = count($scoreArr);
                $item['average_score'] = $count > 0 ? $total / $count : 0;
                $item['warning_ratio'] = round(($item['warning']/$ratingScaleInfo['num'])*100,2);
                $item['normal_ratio'] = round(($item['normal']/$ratingScaleInfo['num'])*100,2);
            }
            $ratingScaleInfo['boy'] = 0;
            $ratingScaleInfo['girl'] = 0;
            $sex = $SelfEvaluationResultModel->field('id,uid')->where('id','in',$ids)->with([
                'user2'
            ])->select()->toArray();
            foreach ($sex as $v){
                if ($v['sex'] == 1){
                    $ratingScaleInfo['boy']++;
                }else{
                    $ratingScaleInfo['girl']++;
                }
            }
            return success($ratingScaleInfo);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 他人代测报告列表excel导出
     * @return bool|string
     */
    public function proxyExcel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $where[] = ['id','in',$param['id']];
            $ReportExportService = new ReportExportService($this->app);
            if (!$ReportExportService->proxyExcel($where,$this->userData['unit_id'])) throw new \Exception($ReportExportService->message);
            return success($ReportExportService->data['fileUrl']??'');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 自我报告列表excel导出
     * @return bool|string
     */
    public function selfExcel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $where[] = ['id','in',$param['id']];
            $ReportExportService = new ReportExportService($this->app);
            if (!$ReportExportService->selfExcel($where,$this->userData['unit_id'])) throw new \Exception($ReportExportService->message);
            return success($ReportExportService->data['fileUrl']??'');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务报告列表excel导出
     * @return bool|string
     */
    public function taskExcel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'uid|用户' => 'require',
            ]);
            $where = [
                ['task_id','=',$param['task_id']],
                ['rating_scale_id','=',$param['rating_scale_id']],
                ['uid','in',$param['uid']]
            ];
            $ReportExportService = new ReportExportService($this->app);
            if (!$ReportExportService->taskExcel($where,$this->userData['unit_id'])) throw new \Exception($ReportExportService->message);
            return success($ReportExportService->data['fileUrl']??'');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务多个量表团体报告导出-前端生成图片的数据
     * @return bool|string
     */
    public function taskAllData(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $TaskModel = new TaskModel();
            $TaskUserResultModel = new TaskUserResultModel();
            $taskInfo = $TaskModel->find($param['id']);
            $uid = $TaskUserResultModel->where('task_id', '=', $param['id'])->distinct(true)->column('uid');
            $data['target_num'] = $taskInfo['user_count'];
            $data['involved_num'] = count($uid);
            $data['not_involved_num'] = $taskInfo['user_count'] - $data['involved_num'];


            $data['report_num'] = $TaskUserResultModel->where('task_id', '=', $param['id'])->count();
            $data['warning_report_num'] = $TaskUserResultModel->where([
                ['task_id', '=', $param['id']],
                ['is_warning', '=', 1]
            ])->count();
            $data['invalid_report_num'] = $TaskUserResultModel->where([
                ['task_id', '=', $param['id']],
                ['is_valid', '=', 0]
            ])->count();
            $data['normal_report_num'] = $data['report_num'] - $data['warning_report_num'] - $data['invalid_report_num'];

            $list = $TaskUserResultModel->field('id,rating_scale_id')->where('task_id', '=', $param['id'])->with([
                'TaskFactorScore' => function ($query) {
                    $query->field('result_id,factor_id,is_warning')->with([
                        'fourInOneRatingScaleFactor'
                    ]);
                }
            ])->select()->toArray();
            $ratingScaleData = [];
            foreach ($list as $item) {
                foreach ($item['TaskFactorScore'] as $v) {
                    if ($v['is_warning']) {
                        if (!isset($ratingScaleData[$item['rating_scale_id']][$v['factor_name']])) {
                            $ratingScaleData[$item['rating_scale_id']][$v['factor_name']] = 0;
                        }
                        $ratingScaleData[$item['rating_scale_id']][$v['factor_name']]++;
                    }
                }
            }
            $RatingScaleModel = new RatingScaleModel();
            foreach ($ratingScaleData as $key => $ratingScale) {
                $name = [];
                $value = [];
                foreach ($ratingScale as $k => $v) {
                    $name[] = $k;
                    $value[] = $v;
                }
                $chart['rating_scale_name'] = $RatingScaleModel->where('id', '=', $key)->value('name');
                $chart['name'] = $name;
                $chart['value'] = $value;
                $data['chartList'][] = $chart;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务多个量表团体报告导出
     * @return bool|string
     */
    public function taskAll(): bool|string
    {
        try {
            $param = $this->request->param();
            $ReportExportService = new ReportExportService($this->app);
            if (!$ReportExportService->taskAll($param)) throw new \Exception($ReportExportService->message);
            return success($ReportExportService->data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 预警报告列表excel导出
     * @return bool|string
     */
    public function warningExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            if (!is_array($param['id'])) throw new \Exception('参数错误！');
            $ReportExportService = new ReportExportService($this->app);
            if (!$ReportExportService->warning($param['id'], $this->userData['unit_id'])) throw new \Exception($ReportExportService->message);
            return success($ReportExportService->data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 四合一（教师）
     * @return bool|string
     */
    public function fourInOne(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $ReportExportService = new ReportExportService($this->app);
            if (!$ReportExportService->fourInOne($param['id'])) throw new \Exception($ReportExportService->message);
            return success($ReportExportService->data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 四合一（小学生）
     * @return bool|string
     */
    public function fourInOne2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $ReportExportService = new ReportExportService($this->app);
            if (!$ReportExportService->fourInOne2($param['id'],$this->userData['unit_id'])) throw new \Exception($ReportExportService->message);
            return success($ReportExportService->data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
    /**
     * 四合一（中学生）
     * @return bool|string
     */
    public function fourInOne3(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $ReportExportService = new ReportExportService($this->app);
            if (!$ReportExportService->fourInOne3($param['id'],$this->userData['unit_id'])) throw new \Exception($ReportExportService->message.$ReportExportService->line);
            return success($ReportExportService->data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取本级部门用户
     * @return bool|string
     */
    public function getCurrentLevelUser(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
            ]);
            $UserModel = new UserModel();
            $whereResult = [];
            $whereResult[] = ['unit_id', '=', $this->userData['unit_id']];
            $whereResult[] = ['task_id', '=', $param['task_id']];
            $whereResult[] = ['rating_scale_id', '=', $param['rating_scale_id']];
            if (isset($param['answer_role']) && strlen($param['answer_role']) > 0) {
                $whereResult[] = ['answer_role', '=', $param['answer_role']];
            }
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                $whereResult[] = ['is_warning', '=', $param['is_warning']];
            }
            if (isset($param['is_explain']) && strlen($param['is_explain']) > 0) {
                $whereResult[] = ['is_explain', '=', $param['is_explain']];
            }
            if (!empty($param['warning_factor_id'])) {
                $whereResult[] = ['warning_factor_id', '=', $param['warning_factor_id']];
            }
            $whereTaskUser = [];
            $whereTaskUser[] = ['task_id', '=', $param['task_id']];
            $whereTaskUser[] = ['rating_scale_id', '=', $param['rating_scale_id']];
            if (!empty($param['name']) || !empty($param['sex'])) {
                $whereUser = [];
                if (!empty($param['name'])) {
                    $whereUser[] = ['name', 'like', '%' . $param['name'] . '%'];
                }
                if (!empty($param['sex'])) {
                    $whereUser[] = ['sex', '=', $param['sex']];
                }
                $uid = $UserModel->where($whereUser)->column('id');
                if (!empty($uid)) {
                    $whereTaskUser[] = ['uid', 'in', $uid];
                } else {
                    $whereTaskUser[] = ['id', '=', -1];
                }
            }
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->field('id,name')->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['pid', '=', $param['pid'] ?? 0]
            ])->with([
                'users' => function ($query) {
                    $query->field('id,department_id,name,sex,age,user_number');
                }
            ])->select()->toArray();
            $TaskUserModel = new TaskUserModel();
            $TaskUserList = $TaskUserModel->field('uid,is_finish,result_id')->where($whereTaskUser)->select()->toArray();
            $userData = [];
            foreach ($TaskUserList as $v) {
                $userData[$v['uid']] = [
                    'is_finish' => $v['is_finish'],
                    'result_id' => $v['result_id']
                ];
            }

            $TaskUserResultModel = new TaskUserResultModel();
            $ResultList = $TaskUserResultModel->field('id,is_warning,is_explain')->where($whereResult)->select()->toArray();
            $resultData = [];
            foreach ($ResultList as $v) {
                $resultData[$v['id']] = [
                    'is_warning' => $v['is_warning'],
                    'is_explain' => $v['is_explain']
                ];
            }

            foreach ($data as $k => &$v) {
                foreach ($v['users'] as $key => &$item) {
                    if (!isset($userData[$item['id']])) {
                        unset($data[$k]['users'][$key]);
                        continue;
                    }
                    $item['is_finish'] = $userData[$item['id']]['is_finish'];
                    $item['result_id'] = $userData[$item['id']]['result_id'];
                    if (!isset($resultData[$item['result_id']]) && $item['is_finish'] == 1) {
                        unset($data[$k]['users'][$key]);
                        continue;
                    }
                    if ($item['is_finish'] == 1) {
                        $item['is_warning'] = $resultData[$item['result_id']]['is_warning'];
                        $item['is_explain'] = $resultData[$item['result_id']]['is_explain'];
                    } else {
                        $item['is_warning'] = 0;
                        $item['is_explain'] = 1;
                    }
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 发布人身份选择器
     * @return bool|string
     */
    public function PublisherSelector(): bool|string
    {
        try {
            $mode = [
                0 => '超级管理员',
                1 => '普通管理员',
                2 => '咨询师',
                3 => '用户'
            ];
            $TaskModel = new TaskModel();
            $uids = $TaskModel->where('unit_id', '=', $this->userData['unit_id'])->column('uid');
            $UserModel = new NotDelUserModel();
            $role_mode = $UserModel->where('id', 'in', $uids)->column('role_mode');
            $role_mode = array_unique($role_mode);
            $data = [];
            foreach ($role_mode as $item) {
                $data[] = [
                    'id' => $item,
                    'name' => $mode[$item]
                ];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 发布人选择器
     * @return bool|string
     */
    public function PublisherSelector2(): bool|string
    {
        try {
            $TaskModel = new TaskModel();
            $uid = $TaskModel->where('unit_id', '=', $this->userData['unit_id'])->column('uid');
            $uid = array_unique($uid);
            $UserModel = new NotDelUserModel();
            $data = $UserModel->field('id,name')
                ->where('id', 'in', $uid)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 完成情况选择器
     * @return bool|string
     */
    public function CompletionStatusSelector(): bool|string
    {
        try {
            $TaskService = new TaskService($this->app);
            return success($TaskService->CompletionStatus());
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 量表因子选择器
     * @return bool|string
     */
    public function RatingScaleFactorSelector(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleModel = new RatingScaleModel();
            $info = $RatingScaleModel->field('id,mode_id')->find($id);
            $RatingScaleFactorModel = new RatingScaleFactorModel();
            $data = $RatingScaleFactorModel->where([
                'rating_scale_id' => $info['id'],
                'mode_id' => $info['mode_id']
            ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取量表详情
     * @return false|string
     */
    public function getTaskRatingScaleInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleModel = new NotDelRatingScaleModel();
            $info = $RatingScaleModel->field('id,name,introduce,notice')->find($id);
            $RatingScaleService = new RatingScaleService($this->app);
            $question = $RatingScaleService->GetQuestion($id);
            return success([
                'question' => $question,
                'info' => $info
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 量表包选择器
     * @return bool|string
     */
    public function ratingScalePackSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['use_scene'])) {
                foreach ($param['use_scene'] as $value) {
                    $RatingScaleWhere[] = ['use_scene', 'like', '%' . $value . '%', 'or'];
                }
            }
            $RatingScaleWhere[] = ['unit_id', '=', $this->userData['unit_id']];
            $RatingScaleWhere[] = ['status', '=', 1];
            $RatingScaleModel = new RatingScaleModel();
            $rating_scale_id = $RatingScaleModel->where($RatingScaleWhere)->column('id');
            if (!empty($rating_scale_id)) {
                $RatingScalePackModel = new RatingScalePackModel();
                $pack_info_id = $RatingScalePackModel->where('rating_scale_id', 'in', $rating_scale_id)->column('pack_info_id');
                if (!empty($pack_info_id)) {
                    $where[] = ['id', 'in', $pack_info_id];
                } else {
                    $where[] = ['id', '=', -1];
                }
            } else {
                $where[] = ['id', '=', -1];
            }
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['status', '=', 1];
            $RatingScalePackInfoModel = new RatingScalePackInfoModel();
            $list = $RatingScalePackInfoModel->field('id,name')
                ->where($where)->withCount('RatingScalePack')->select()->toArray();
            foreach ($list as $key => $item) {
                if ($item['rating_scale_pack_count'] == 0) {
                    unset($list[$key]);
                }
            }
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 量表选择器
     * @return bool|string
     */
    public function ratingScaleSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $RatingScaleWhere = [];
            if (!empty($param['name'])) {
                $RatingScaleWhere[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['use_scene'])) {
                foreach ($param['use_scene'] as $value) {
                    $RatingScaleWhere[] = ['use_scene', 'like', '%' . $value . '%', 'or'];
                }
            }
            $RatingScaleWhere[] = ['unit_id', '=', $this->userData['unit_id']];
            $RatingScaleWhere[] = ['status', '=', 1];
            $RatingScaleModel = new RatingScaleModel();
            $type_id = $RatingScaleModel->where($RatingScaleWhere)->column('type_id');
            if (!empty($type_id)) {
                $where[] = ['id', 'in', $type_id];
            } else {
                $where[] = ['id', '=', -1];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['status', '=', 1];
            $RatingScaleTypeModel = new RatingScaleTypeModel();
            $list = $RatingScaleTypeModel->field('id,name')
                ->where($where)
                ->with([
                    'RatingScale' => function ($query) {
                        $query->field('id,type_id,name,mode_id');
                    }
                ])->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 用户选择器
     * @return bool|string
     */
    public function userSelector(): bool|string
    {
        try {
            $where = [];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $DepartmentModel = new DepartmentModel();
            if ($this->userData['role_id'] > 0) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $DepartmentIds = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                if (!empty($DepartmentIds)) {
                    $UserService = new UserService($this->app);
                    $DepartmentIds = $UserService->getDepartmentAuthId($this->userData['unit_id'], $DepartmentIds);
                    $where[] = ['id', 'in', $DepartmentIds];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $data = $DepartmentModel->field('id,pid,name')->where($where)
                ->with([
                    'users' => function ($query) {
                        $query->field('id,department_id,name,sex,age,user_number');
                    }
                ])->select()->toArray();
            if (!empty($data)) {
                $data2[] = [
                    'id' => 0,
                    'name' => $this->userData['unit']['name'] ?? '',
                    'child' => buildTree($data),
                    'users' => []
                ];
            } else {
                $data2 = [];
            }
            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务详情
     * @return bool|string
     */
    public function TaskInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserModel = new TaskUserModel();
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskContinuousEvaluation = new TaskContinuousEvaluationModel();
            $task = $this->mode->find($id)->toArray();
            $task['result_read_auth'] = explode(',', $task['result_read_auth']);
            $uids = $TaskUserModel->where('task_id', $id)->distinct(true)->column('uid');
            $TaskRatingScaleList = $TaskRatingScaleModel->where('task_id', $id)
                ->with([
                    'ratingScale',
                    'ratingScalePack'
                ])->select()->toArray();
            $factorList = $TaskContinuousEvaluation->where('task_id', $id)
                ->with([
                    'RatingScale', 'RatingScaleFactor', 'continuityRatingScale'
                ])->select()->toArray();
            $factorData = [];
            foreach ($factorList as $item) {
                $factorData[$item['rating_scale_id']][] = [
                    'factor_id' => $item['factor_id'],
                    'factor_name' => $item['factor_name'],
//                    'rating_scale_id' => $item['rating_scale_id'],
//                    'rating_scale_name' => $item['rating_scale_name'],
                    'rating_scale_id' => $item['continuity_rating_scale_id'],
                    'rating_scale_name' => $item['continuity_rating_scale_name'],
                ];
            }
            $rating_scale = [];
            foreach ($TaskRatingScaleList as $item) {
                $rating_scale[] = [
                    'id' => $item['rating_scale_id'],
                    'name' => $item['rating_scale_name'],
                    'pack_id' => $item['pack_id'],
                    'pack' => $item['rating_scale_pack_name'],
                    'factor' => $factorData[$item['rating_scale_id']] ?? []
                ];
            }
            if (!empty($task['jsondata'])) {
                $jsondata = json_decode($task['jsondata'], true);
            } else {
                $jsondata = [];
            }
            return success([
                'task' => $task,
                'uids' => $uids,
                'rating_scale' => $rating_scale,
                'uidsLevel' => $jsondata,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 发布任务
     * @return false|string
     */
    public function releaseTask(): bool|string
    {
        $this->mode->startTrans();
        try {
            $taskData = $this->request->param('task');
            $rating_scale = $this->request->param('rating_scale');
            $uids = $this->request->param('uids');
            $uidsLevel = $this->request->param('uidsLevel');
            $this->validate($taskData, $this->mode->addValidate());
            if (empty($uids)) throw new \Exception('请选择用户！');
            if (empty($rating_scale)) throw new \Exception('请选择量表！');
            $rating_scale_column = array_column($rating_scale, 'id');
            if (count($rating_scale_column) !== count(array_unique($rating_scale_column))) throw new \Exception('量表不能重复选择！');
            $taskData['rating_scale_count'] = count($rating_scale);
            $taskData['user_count'] = count($uids);
            $taskData['unit_id'] = $this->userData['unit_id'];
            $taskData['uid'] = $this->userData['id'];
            $taskData['time'] = $time = time();
            if (!empty($uidsLevel)) {
                $taskData['jsondata'] = json_encode($uidsLevel, true);
            }
            if (!empty($taskData['is_time']) && $taskData['is_time'] == 1) {
                if (empty($taskData['start_time']) || empty($taskData['end_time'])) throw new \Exception('请填写开始和结束时间！');
                if ($taskData['start_time'] <= $time && $taskData['end_time'] >= $time) {
                    //在任务时间内将任务设为进行中
                    $taskData['status'] = 2;
                }
            } else {
                $taskData['status'] = 2;
            }
            if (!empty($taskData['result_read_auth'])) {
                $taskData['result_read_auth'] = implode(',', $taskData['result_read_auth']);
            }
            $ConfigModel = new ConfigModel();
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'evaluation_task'
            ])->value('value') ?? '';
            $config = json_decode($data, true);
            if (isset($config['is_continuous'])) {
                $taskData['is_continuous'] = $config['is_continuous'] ? 1 : 0;
            }
            $taskData['is_redo'] = $config['is_redo'] ?? 0;
            $taskData['is_temporary'] = $config['is_temporary'] ?? 0;
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskUserModel = new TaskUserModel();
            $TaskContinuousEvaluation = new TaskContinuousEvaluationModel();
            $task_id = $this->mode->insertGetId($taskData);
            //添加任务量表和任务用户
            $task_user = [];
            $task_rating_scale = [];
            $continuousData = [];
            $MessageData = [];
            foreach ($rating_scale as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    if ($item['id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                    $continuousData[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $time
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
                    'task_id' => $task_id,
                    'rating_scale_id' => $item['id'],
                    'pack_id' => $item['pack_id'],
                    'time' => $time
                ];
                //任务用户
                foreach ($uids as $uid) {
                    $task_user[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'uid' => $uid,
                        'time' => $time
                    ];
                    $MessageData[] = [
                        'uid' => $uid,
                        'type' => 3,
                        'title' => '发布任务',
                        'content' => $this->userData['name'] . '管理员发布了' . $taskData['name'] . '任务，请及时查看并完成测评任务。',
                        'time' => time()
                    ];
                }
            }
            if (!empty($continuousData)) {
                $TaskContinuousEvaluation->insertAll($continuousData);
            }
            if (!empty($task_user)) {
                $TaskUserModel->insertAll($task_user, 200);
            }
            if (!empty($task_rating_scale)) {
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            $MessageModel = new MessageModel();
            $MessageData[] = [
                'uid' => $this->userData['id'],
                'type' => 3,
                'title' => '发布任务',
                'content' => '您于' . date('Y-m-d') . '日期' . date('H:i:s') . '时间发布的' . $taskData['name'] . '测评任务,已全部向用户推送完成。',
                'time' => time()
            ];
            $MessageModel->insertAll($MessageData, 200);
            $this->mode->commit();
            return success([], '添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 已发布任务列表
     * @return false|string
     */
    public function taskList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['user_complete_rate'])) {
                $TaskService = new TaskService($this->app);
                $CompletionStatus = $TaskService->CompletionStatus($param['user_complete_rate']);
                $where[] = ['user_complete_rate', 'between', $CompletionStatus['value']];
            }
            if (!empty($param['id'])) {
                $where[] = ['id', 'in', $param['id']];
            }
            if (!empty($param['role_mode'])) {
                $UserModel = new UserModel();
                $uid = $UserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['role_mode', '=', $param['role_mode']]
                ])->column('id');
                if (!empty($uid)) {
                    $where[] = ['uid', 'in', $uid];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['code_type', '=', 1];
            $query = $this->mode->where($where);
            $data = $query->with([
                'userNameRoleName' => function ($query) {
                    $query->with(['roleName']);
                }
            ])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                if (empty($item['role_name'])) $item['role_name'] = '超级管理员';
                $item['user_complete_rate'] = $item['user_complete_rate'] . '%';
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑进行中的任务
     * @return bool|string
     */
    public function update2(): bool|string
    {
        try {
            $this->mode->startTrans();
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'uid|用户ID' => 'require'
            ]);
            $info = $this->mode->find($param['task_id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['is_time']) && $param['is_time'] == 1) {
                if (empty($param['end_time'])) throw new \Exception('请填写结束时间！');
                $time = time();
                $param['start_time'] = $info['start_time'];
                if ($param['start_time'] <= $time && $param['end_time'] >= $time) {
                    //在任务时间内将任务设为进行中
                    $info->status = 2;
                }
            } else {
                $info->status = 2;
            }
            $info->end_time = $param['end_time'] ?? 0;
            $info->is_time = $param['is_time'] ?? 0;

            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskRatingScaleData = $TaskRatingScaleModel->where('task_id', '=', $param['task_id'])->column('rating_scale_id');
            $TaskUserModel = new TaskUserModel();
            $uids = $TaskUserModel->where('task_id', '=', $param['task_id'])->column('uid');
            $task_user = [];
            foreach ($param['uid'] as $uid) {
                if (!in_array($uid, $uids)) {
                    foreach ($TaskRatingScaleData as $rating_scale_id) {
                        $task_user[] = [
                            'task_id' => $param['task_id'],
                            'rating_scale_id' => $rating_scale_id,
                            'uid' => $uid,
                            'time' => time()
                        ];
                    }
                }
            }
            if (!empty($task_user)) {
                $TaskUserModel->insertAll($task_user, 200);
            }
            $info->user_count += count($task_user);
            $info->user_complete_rate = round($info->user_complete_num / $info->user_count * 100, 2);
            $info->save();
            $this->mode->commit();
            return success([], '编辑成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑任务
     * @return false|string
     */
    public function update(): bool|string
    {
        try {
            $this->mode->startTrans();
            $task_id = $this->request->param('task_id');
            $info = $this->mode->find($task_id);
            if (!$info) throw new \Exception('参数错误！');
            if ($info->status != 1) throw new \Exception('未开始的任务才能编辑全部信息！');
            $info->is_del = 1;
            $info->del_time = time();
            $info->save();
            $taskData = $this->request->param('task');
            $rating_scale = $this->request->param('rating_scale');
            $uids = $this->request->param('uids');
            $uidsLevel = $this->request->param('uidsLevel');
            $this->validate($taskData, $this->mode->addValidate());
            if (empty($uids)) throw new \Exception('请选择用户！');
            if (empty($rating_scale)) throw new \Exception('请选择量表！');
            $rating_scale_column = array_column($rating_scale, 'id');
            if (count($rating_scale_column) !== count(array_unique($rating_scale_column))) throw new \Exception('量表不能重复选择！');
            $taskData['rating_scale_count'] = count($rating_scale);
            $taskData['user_count'] = count($uids);
            $taskData['unit_id'] = $this->userData['unit_id'];
            $taskData['uid'] = $this->userData['id'];
            $taskData['time'] = $time = time();
            if (!empty($uidsLevel)) {
                $taskData['jsondata'] = json_encode($uidsLevel, true);
            }
            if (!empty($taskData['is_time']) && $taskData['is_time'] == 1) {
                if (empty($taskData['start_time']) || empty($taskData['end_time'])) throw new \Exception('请填写开始和结束时间！');
                if ($taskData['start_time'] <= $time && $taskData['end_time'] >= $time) {
                    //在任务时间内将任务设为进行中
                    $taskData['status'] = 2;
                }
            } else {
                $taskData['status'] = 2;
            }
            if (!empty($taskData['result_read_auth'])) {
                $taskData['result_read_auth'] = implode(',', $taskData['result_read_auth']);
            }
            $ConfigModel = new ConfigModel();
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'evaluation_task'
            ])->value('value') ?? '';
            $config = json_decode($data, true);
            $taskData['is_continuous'] = $config['is_continuous'] ?? 0;
            $taskData['is_redo'] = $config['is_redo'] ?? 0;
            $taskData['is_temporary'] = $config['is_temporary'] ?? 0;
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskUserModel = new TaskUserModel();
            $TaskContinuousEvaluation = new TaskContinuousEvaluationModel();
            unset($taskData['id']);
            $task_id = $this->mode->insertGetId($taskData);
            //添加任务量表和任务用户
            $task_user = [];
            $task_rating_scale = [];
            $continuousData = [];
            foreach ($rating_scale as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    if ($item['id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                    $continuousData[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $time
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
                    'task_id' => $task_id,
                    'rating_scale_id' => $item['id'],
                    'pack_id' => $item['pack_id'],
                    'time' => $time
                ];
                //任务用户
                foreach ($uids as $uid) {
                    $task_user[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'uid' => $uid,
                        'time' => $time
                    ];
                }
            }
            if (!empty($continuousData)) {
                $TaskContinuousEvaluation->insertAll($continuousData);
            }
            if (!empty($task_user)) {
                $TaskUserModel->insertAll($task_user, 200);
            }
            if (!empty($task_rating_scale)) {
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            $this->mode->commit();
            return success([], '添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取任务用户
     * @return false|string
     */
    public function getTaskUser(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $data = $this->getTaskUser2($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function getTaskUser2($id): array
    {
        $TaskUserModel = new TaskUserModel();
        $data = $TaskUserModel->field('uid,is_finish')->where('task_id', '=', $id)->with([
            'taskUser'
        ])->order('is_finish', 'asc')->group('uid')->select()->toArray();
        $departmentIds = array_unique(array_column($data, 'department_id'));
        $UserService = new UserService($this->app);
        $NotDelDepartmentAll = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
        $DepartmentAdminAll = $UserService->getDepartmentAdminAll($departmentIds);
        foreach ($data as &$item) {
            $item['ascription_name'] = $NotDelDepartmentAll[$item['department_id']]['ascription_name'] ?? '';
            $item['department_name'] = $NotDelDepartmentAll[$item['department_id']]['all_name'] ?? '';
            $item['department_admin'] = $DepartmentAdminAll[$item['department_id']]['user_name'] ?? '';
        }
        return $data;
    }

    /**
     * 导出任务用户名单
     * @return false|string
     */
    public function exportTaskUser(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'is_finish|参与状态' => 'require',
                'data|导出数据' => 'require'
            ]);
            $TaskService = new TaskService($this->app);
            return success($TaskService->exportTaskUser($param['data'], $param['is_finish']));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 导出任务用户名单
     * @return false|string
     */
    public function exportTaskUser2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|任务ID' => 'require',
                'is_finish|参与状态' => 'require',
            ]);
            $data = $this->getTaskUser2($param['id']);
            $TaskService = new TaskService($this->app);
            return success($TaskService->exportTaskUser($data, $param['is_finish']));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取任务量表
     * @return false|string
     */
    public function getTaskRatingScale(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $data = $TaskRatingScaleModel->field('id,rating_scale_id')
                ->with(['ratingScale'])
                ->where('task_id', '=', $id)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 查询任务状态
     * @return bool|string
     */
    public function taskStatus(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (is_array($id)) {
                $status = $this->mode->where('id', 'in', $id)->distinct(true)->column('status');
            } else {
                $status = $this->mode->where('id', '=', $id)->distinct(true)->column('status');
            }
            return success($status);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除任务
     * @return false|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (is_array($id)) {
                $this->mode->where('id', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            } else {
                $this->mode->where('id', '=', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 终止任务
     * @return false|string
     */
    public function terminateTask(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $info = $this->mode->find($id);
            if ($info->status == 3) throw new \Exception('任务已终止！');
            $info->status = 3;
            $info->save();
            return success('任务已终止！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 自我测评报告
     * @return false|string
     */
    public function selfEvaluationReportList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $RatingScaleModel = new NotDelRatingScaleModel();
            $UserModel = new NotDelUserModel();
            $DepartmentAdminModel = new DepartmentAdminModel();
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['name'])) {
                $rating_scale_ids = $RatingScaleModel->where('name', 'like', '%' . $param['name'] . '%')->column('id');
                $uids = $UserModel->where('name', 'like', '%' . $param['name'] . '%')->column('id');
                if (count($rating_scale_ids) > 0 || count($uids) > 0) {
                    if (count($rating_scale_ids) > 0) {
                        $where[] = ['rating_scale_id', 'in', $rating_scale_ids];
                    }
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    }
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['type_id'])) {
                $rating_scale_ids = $RatingScaleModel->where('type_id', '=', $param['type_id'])->column('id');
                if (count($rating_scale_ids) > 0) {
                    $where[] = ['rating_scale_id', 'in', $rating_scale_ids];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['answer_role'])) {
                $where[] = ['answer_role', '=', $param['answer_role']];
            }
            if (!empty($param['is_explain'])) {
                $where[] = ['is_explain', '=', $param['is_explain']];
            }
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                $where[] = ['is_warning', '=', $param['is_warning']];
            }
            if (!empty($param['id'])) {
                if (is_array($param['id'])) {
                    $where[] = ['id', 'in', $param['id']];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['admin_del', '=', 0];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $UserService = new UserService($this->app);
            switch ($this->userData['role_mode']) {
                case 1:
                    $departmentIds = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                    $uids = $UserModel->where('department_id', 'in', $departmentIds)->column('id');
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['uid', '=', -1];
                    }
                    break;
                case 2:
                    $where[] = ['id', '=', -1];
                    break;
            }
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $query = $SelfEvaluationResultModel->where($where);
            $data = $query->field('id,uid,rating_scale_id,answer_role,total_score,time,result_read_auth,is_warning,warning_id,is_explain,is_special_group,is_follow,is_interfere')
                ->with([
                    'user' => function ($query) {
                        $query->with([
                            'department' => function ($query) {
                                $query->with([
                                    'departmentAdmins' => function ($query) {
                                        $query->with(['userName']);
                                    }
                                ]);
                            },
                            'unitName']);
                    },
                    'ratingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    },
                    'RatingScaleFactorWarningModel'
                ])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            $departmentIds = array_column($data['data'], 'department_id');
            $NotDelDepartmentAll = $UserService->getDepartmentAffiliationAll2($this->userData['unit_id'], $departmentIds);
            foreach ($data['data'] as &$item) {
                $item['department_admins'] = $item['departmentAdmins'];
                $item['department_name'] = $NotDelDepartmentAll['department_data'][$item['department_id']]['all_name'] ?? '';
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评详情
     * @return bool|string
     */
    public function selfEvaluationReportInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getSelfEvaluationReportInfo($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }

    }


    /**
     * 删除自我测评记录
     * @return bool|string
     */
    public function selfEvaluationReportDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            if (is_array($id)) {
                $SelfEvaluationResultModel->where('id', 'in', $id)->update([
                    'admin_del' => 1,
                ]);
            } else {
                $SelfEvaluationResultModel->where('id', '=', $id)->update([
                    'admin_del' => 1,
                ]);
            }
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告
     * @return false|string
     */
    public function taskEvaluationReportList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $whereOr = [];
            $ResultWhere = [];
            if (!empty($param['name'])) {
                $task_id = $this->mode->where([
                    ['name', 'like', '%' . $param['name'] . '%'],
                    ['unit_id', '=', $this->userData['unit_id']]
                ])->column('id');
                $whereOr[] = ['task_id', 'in', $task_id];
                $RatingScaleModel = new RatingScaleModel();
                $RatingScaleIds = $RatingScaleModel->where([
                    ['name', 'like', '%' . $param['name'] . '%'],
                    ['unit_id', '=', $this->userData['unit_id']]
                ])->column('id');
                $whereOr[] = ['rating_scale_id', 'in', $RatingScaleIds];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['start_time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['start_time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['start_time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['start_time2']) && !empty($param['end_time2'])) {
                $where[] = ['time', 'between', [$param['start_time2'], $param['end_time2']]];
            } else {
                if (!empty($param['start_time2'])) {
                    $where[] = ['time', '>=', $param['start_time2']];
                }
                if (!empty($param['end_time2'])) {
                    $where[] = ['time', '<=', $param['end_time2']];
                }
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', '=', $param['uid']];
            }
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                if ($param['is_warning'] == 1) {
                    $where[] = ['warning_num', '>', 0];
                } else {
                    $where[] = ['warning_num', '=', 0];
                }
            }
            $ResultWhere[] = ['unit_id', '=', $this->userData['unit_id']];
            $ResultWhere[] = ['admin_del', '=', 0];
            $UserModel = new NotDelUserModel();
            $DepartmentAdminModel = new DepartmentAdminModel();
            switch ($this->userData['role_mode']) {
                case 1:
                    $departmentIds = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->distinct(true)->column('department_id');
                    $uid = $UserModel->where('department_id', 'in', $departmentIds)->column('id');
                    if (!empty($uid)) {
                        $ResultWhere[] = ['uid', 'in', $uid];
                    } else {
                        $ResultWhere[] = ['uid', '=', -1];
                    }
                    break;
                case 2:
                    $ResultWhere[] = ['id', '=', -1];
                    break;
            }
            $TaskUserResultModel = new TaskUserResultModel();
            $TaskIds = $TaskUserResultModel->where($ResultWhere)->whereOr($whereOr)->distinct(true)->column('task_id');
            if (!empty($TaskIds)) {
                $where[] = ['id', 'in', $TaskIds];
            } else {
                $where[] = ['id', '=', -1];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->field('id,uid,name,rating_scale_count,user_count,start_time,end_time,user_complete_num,result_read_auth,warning_num,user_complete_rate,time')
                ->with(['userName'])
                ->withCount(['AnswerRoleUser', 'AnswerRoleParent'])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['answer_role'] = $TaskUserResultModel->where([
                    ['task_id', '=', $item['id']],
                    ['answer_role', '=', 1]
                ])->count();
                $item['answer_role2'] = $TaskUserResultModel->where([
                    ['task_id', '=', $item['id']],
                    ['answer_role', '=', 2]
                ])->count();
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除任务测评报告
     * @return bool|string
     */
    public function taskEvaluationReportDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserResultModel = new TaskUserResultModel();
            if (is_array($id)) {
                $uids = $this->mode->where('id', 'in', $id)->distinct(true)->column('uid');
                if (!in_array($this->userData['id'], $uids) || count($uids) > 1) throw new \Exception('任务发布人才能删除！');
                $TaskUserResultModel->where('task_id', 'in', $id)->update([
                    'admin_del' => 1,
                ]);
            } else {
                $uid = $this->mode->where('id', '=', $id)->value('uid');
                if ($uid != $this->userData['id']) throw new \Exception('任务发布人才能删除！');
                $TaskUserResultModel->where('task_id', '=', $id)->update([
                    'admin_del' => 1,
                ]);
            }
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 任务测评报告详情
     * @return bool|string
     */
    public function taskEvaluationReportInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskModel = new TaskModel();
            $TaskInfo = $TaskModel->with([
                'userNameRoleName' => function ($query) {
                    $query->with(['roleName']);
                }
            ])->find($id);
            if (!$TaskInfo) throw new \Exception('未查询到任务！');
            $TaskInfo = $TaskInfo->toArray();
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskRatingScaleList = $TaskRatingScaleModel->where('task_id', '=', $id)
                ->with([
                    'ratingScale'
                ])->select()->toArray();

            if (empty($TaskInfo['role_name'])) $TaskInfo['role_name'] = '超级管理员';
            $TaskUserResultModel = new TaskUserResultModel();
            $TaskInfo['answer_role'] = $TaskUserResultModel->where([
                ['task_id', '=', $TaskInfo['id']],
                ['answer_role', '=', 1]
            ])->count();
            $TaskInfo['answer_role2'] = $TaskUserResultModel->where([
                ['task_id', '=', $TaskInfo['id']],
                ['answer_role', '=', 2]
            ])->count();
            return success([
                'TaskInfo' => $TaskInfo,
                'TaskRatingScaleList' => $TaskRatingScaleList
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除任务对应量表的报告
     * @return bool|string
     */
    public function taskRatingScaleReportDel(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $TaskUserResultModel = new TaskUserResultModel();
            $TaskUserResultModel->where([
                'task_id' => $task_id,
                'rating_scale_id' => $rating_scale_id
            ])->update([
                'admin_del' => 1,
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务量表详情-左测概况
     * @return bool|string
     */
    public function TaskRatingScaleLeftSurvey(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskRatingScaleInfo = $TaskRatingScaleModel->with(['ratingScale', 'task'])->find($id)->toArray();
            $TaskUserResultModel = new TaskUserResultModel();
            $TaskRatingScaleInfo['answer_role'] = $TaskUserResultModel->where([
                ['task_id', '=', $TaskRatingScaleInfo['task_id']],
                ['rating_scale_id', '=', $TaskRatingScaleInfo['rating_scale_id']],
                ['answer_role', '=', 1]
            ])->count();
            $TaskRatingScaleInfo['answer_role2'] = $TaskUserResultModel->where([
                ['task_id', '=', $TaskRatingScaleInfo['task_id']],
                ['rating_scale_id', '=', $TaskRatingScaleInfo['rating_scale_id']],
                ['answer_role', '=', 2]
            ])->count();
            return success($TaskRatingScaleInfo);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务测评用户部门
     * @return bool|string
     */
    public function TaskEvaluationUserDepartment(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require'
            ]);

            // 模型实例化
            $TaskUserResultModel = new TaskUserResultModel();
            $UserModel = new NotDelUserModel();
            $TaskUserModel = new TaskUserModel();
            $DepartmentModel = new NotDelDepartmentModel();

            // 基础查询条件
            $where = [
                ['task_id', '=', $param['task_id']],
                ['rating_scale_id', '=', $param['rating_scale_id']]
            ];

            // 获取所有任务用户列表（作为基础数据集）
            $taskUserList = $TaskUserModel->field('id,uid,result_id,is_finish')
                ->where($where)->select()->toArray();

            if (empty($taskUserList)) {
                return success([]);
            }

            // 提取所有用户ID和结果ID
            $allUids = array_unique(array_column($taskUserList, 'uid'));
            $allResultIds = array_unique(array_column($taskUserList, 'result_id'));

            // 检测是否存在搜索条件（用户相关或结果相关）
            $hasUserSearch = !empty($param['name']) || !empty($param['sex']);
            $hasResultSearch = isset($param['answer_role']) && strlen($param['answer_role']) > 0
                || isset($param['is_warning']) && strlen($param['is_warning']) > 0
                || isset($param['is_explain']) && strlen($param['is_explain']) > 0
                || !empty($param['warning_factor_id']);

            $hasAnySearch = $hasUserSearch || $hasResultSearch;

            // 1. 筛选符合条件的用户ID（用户表条件）
            $validUserIds = $allUids; // 默认全部用户ID有效
            if ($hasUserSearch) {
                $userWhere = [['id', 'in', $allUids]];
                if (!empty($param['name'])) {
                    $userWhere[] = ['name', 'like', '%' . $param['name'] . '%'];
                }
                if (!empty($param['sex'])) {
                    $userWhere[] = ['sex', '=', $param['sex']];
                }
                $validUserIds = $UserModel->where($userWhere)->column('id');
            }
            $validUserIdsMap = array_flip($validUserIds); // 转为键值以便快速查找

            // 2. 筛选符合条件的结果ID（结果表条件）
            $validResultIds = $allResultIds; // 默认全部结果ID有效
            if ($hasResultSearch) {
                $resultWhere = [['id', 'in', $allResultIds]];
                if (isset($param['answer_role']) && strlen($param['answer_role']) > 0) {
                    $resultWhere[] = ['answer_role', '=', $param['answer_role']];
                }
                if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                    $resultWhere[] = ['is_warning', '=', $param['is_warning']];
                }
                if (isset($param['is_explain']) && strlen($param['is_explain']) > 0) {
                    $resultWhere[] = ['is_explain', '=', $param['is_explain']];
                }
                if (!empty($param['warning_factor_id'])) {
                    $resultWhere[] = ['warning_factor_id', '=', $param['warning_factor_id']];
                }
                $validResultIds = $TaskUserResultModel->where($resultWhere)->column('id');
            }
            $validResultIdsMap = array_flip($validResultIds); // 转为键值以便快速查找

            // 3. 根据是否有搜索条件应用不同的逻辑关系
            $filteredTaskUsers = [];
            foreach ($taskUserList as $taskUser) {
                if ($hasAnySearch) {
                    // 有搜索条件：应用"且"关系（同时满足用户和结果条件）
                    if (isset($validUserIdsMap[$taskUser['uid']]) && isset($validResultIdsMap[$taskUser['result_id']])) {
                        $filteredTaskUsers[] = $taskUser;
                    }
                } else {
                    // 无搜索条件：应用"或"关系（实际上这里默认全部通过，因为没有任何过滤条件）
                    $filteredTaskUsers[] = $taskUser;
                }
            }

            if (empty($filteredTaskUsers)) {
                return success([]);
            }

            // 提取过滤后的ID用于后续查询
            $uids = array_unique(array_column($filteredTaskUsers, 'uid'));
            $resultIds = array_unique(array_column($filteredTaskUsers, 'result_id'));

            // 分块查询用户信息并构建映射
            $userMap = [];
            $chunkSize = 200;
            $uidChunks = array_chunk($uids, $chunkSize);

            foreach ($uidChunks as $chunk) {
                $users = $UserModel->field('id,name,age,sex,department_id')
                    ->where('id', 'in', $chunk)->select()->toArray();

                foreach ($users as $user) {
                    $userMap[$user['id']] = $user;
                }
            }

            // 分块查询结果信息并构建映射
            $resultMap = [];
            $resultChunks = array_chunk($resultIds, $chunkSize);

            foreach ($resultChunks as $chunk) {
                $results = $TaskUserResultModel->field('id,is_explain,is_warning')
                    ->where('id', 'in', $chunk)->select()->toArray();

                foreach ($results as $result) {
                    $resultMap[$result['id']] = $result;
                }
            }

            // 整合数据并按部门分组
            $department = [];
            foreach ($filteredTaskUsers as $taskUser) {
                // 合并用户信息
                if (isset($userMap[$taskUser['uid']])) {
                    $userInfo = $userMap[$taskUser['uid']];
                    $taskUser['user_name'] = $userInfo['name'];
                    $taskUser['age'] = $userInfo['age'];
                    $taskUser['sex'] = $userInfo['sex'];
                    $taskUser['department_id'] = $userInfo['department_id'];
                }

                // 合并结果信息
                if (isset($resultMap[$taskUser['result_id']])) {
                    $taskUser['is_explain'] = $resultMap[$taskUser['result_id']]['is_explain'];
                    $taskUser['is_warning'] = $resultMap[$taskUser['result_id']]['is_warning'];
                }

                // 按部门ID分组
                if (!empty($taskUser['department_id'])) {
                    $deptId = $taskUser['department_id'];
                    if (!isset($department[$deptId])) {
                        $department[$deptId] = ['user_list' => []];
                    }
                    $department[$deptId]['user_list'][] = $taskUser;
                }
            }

            // 获取部门授权ID
            $departmentIds = array_keys($department);
            $UserService = new UserService($this->app);
            if (!empty($param['unit_id'])){
                $unitId = $param['unit_id'];
                $UnitModel = new UnitModel();
                $unitName = $UnitModel->where('id','=',$param['unit_id'])->value('name');
            }else{
                $unitId = $this->userData['unit_id'];
                $unitName = $this->userData['unit']['name'];
            }
            $authorizedDeptIds = $UserService->getDepartmentAuthId($unitId, $departmentIds);

            // 分块查询部门信息
            $deptData = [];
            $deptChunks = array_chunk($authorizedDeptIds, $chunkSize);
            foreach ($deptChunks as $chunk) {
                $deptChunkData = $DepartmentModel->field('id,pid,name')
                    ->where('id', 'in', $chunk)->select()->toArray();
                $deptData = array_merge($deptData, $deptChunkData);
            }

            // 为部门添加用户列表
            foreach ($deptData as &$item) {
                $item['user_list'] = $department[$item['id']]['user_list'] ?? [];
            }
            unset($item); // 解除引用

            // 构建部门树
            $data2 = buildTree($deptData);

            $data3 = [
                [
                    'id' => 0,
                    'name' => $unitName,
                    'child' => $data2,
                    'user_list' => []
                ]
            ];

            return success($data3);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告详情
     * @return bool|string
     */
    public function TaskEvaluationReport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getTaskReportInfo($id);
            if (empty($data) || $data['admin_del'] == 1) throw new \Exception('报告已被删除！');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 连续测评结果列表
     * @return bool|string
     */
    public function ContinuousEvaluationResultsList(): bool|string
    {
        try {
            $task_user_id = $this->request->param('task_user_id');
            $TaskUserResultContinuityModel = new TaskUserResultContinuityModel();
            $data = $TaskUserResultContinuityModel->field('id,rating_scale_id,uid,answer_role,total_score,finish_used_time,is_warning,warning_id,is_follow,is_explain,result_read_auth,time,evaluation_fee,interpretation_fee')
                ->where('task_user_id', '=', $task_user_id)
                ->with([
                    'RatingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    },
                ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 连续测评结果详情
     * @return bool|string
     */
    public function ContinuousEvaluationResultsInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserResultContinuityModel = new TaskUserResultContinuityModel();
            $data = $TaskUserResultContinuityModel->field('id,rating_scale_id,uid,answer_role,total_score,finish_used_time,is_warning,warning_id,is_follow,is_explain,result_read_auth,time,evaluation_fee,interpretation_fee')
                ->with([
                    'RatingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    },
                    'user' => function ($query) {
                        $query->with([
                            'department' => function ($query) {
                                $query->with([
                                    'departmentAdmins' => function ($query) {
                                        $query->with(['userName']);
                                    }
                                ]);
                            }
                        ]);
                    },
                    'RatingScaleFactorWarningModel' => function ($query) {
                        $query->with(['factorName']);
                    },
                    'TaskFactorScoreContinuity' => function ($query) {
                        $query->with(['RatingScaleFactor', 'RatingScaleFactorLevel']);
                    }
                ])->find($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 他人代测
     * @return bool|string
     */
    public function ProxyTesting(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'uid|用户ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'answer_role|答题角色' => 'require',
                'question_answer|用户填写的答案' => 'require',
                'finish_used_time|用户完成用时' => 'require',
            ]);
            $UserRatingScaleService = new UserRatingScaleService($this->app);
            if (!$UserRatingScaleService->generateReport([
                'company_id' => $this->userData['company_id'],
                'areas_id' => $this->userData['areas_id'],
                'unit_id' => $this->userData['unit_id'],
                'proxy_uid' => $this->userData['id'],//代测人
                'uid' => $param['uid'],//答题用户ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'answer_role' => $param['answer_role'],//答题角色【1 用户，2 家长】
                'userAnswer' => $param['question_answer'],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
            ], 4))
                throw new \Exception('提交失败！' . $UserRatingScaleService->message);
            $this->mode->commit();
            return success([
                'result_id' => $UserRatingScaleService->ResultId,
                'is_valid' => $UserRatingScaleService->is_valid
            ], '提交成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 账号获取用户信息
     * @return bool|string
     */
    public function usernameGetInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'username|账号' => 'require',
                'password|密码' => 'require',
            ]);
            $UserModel = new NotDelUserModel();
            $user = $UserModel->where('username', '=', $param['username'])->with([
                'departmentName', 'unitName'
            ])->find();
            if (!$user) throw new \Exception('账号或密码错误！');
            $newPassword = encrypt_password($param['password']);
            if ($user['password'] != $newPassword) throw new \Exception('账号或密码错误！');
            if ($user['status'] != 1) throw new \Exception('账号异常！');
            if ($user['role_mode'] != 3) throw new \Exception('只能帮普通用户预约！');
            return success($user);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * UID获取用户信息
     * @return bool|string
     */
    public function uidGetInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'uid|用户ID' => 'require',
            ]);
            $UserModel = new NotDelUserModel();
            $user = $UserModel->with([
                'departmentName', 'unitName', 'roleName'
            ])->find($param['uid']);
            if (!$user || $user['status'] != 1) throw new \Exception('账号异常！');
            if (!$user['role_name']) $user['role_name'] = '超级管理员';
            return success($user);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 代测人选择器
     * @return bool|string
     */
    public function proxyUserSelector(): bool|string
    {
        try {
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $proxy_uid = $ProxyEvaluationResultModel->where('unit_id', '=', $this->userData['unit_id'])->column('proxy_uid');
            $UserModel = new NotDelUserModel();
            $data = $UserModel->field('id,name')->where('id', 'in', $proxy_uid)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 他人代测报告列表
     * @return bool|string
     */
    public function ProxyTestingReportList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $RatingScaleModel = new NotDelRatingScaleModel();
            $UserModel = new NotDelUserModel();
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['name'])) {
                $rating_scale_ids = $RatingScaleModel->where('name', 'like', '%' . $param['name'] . '%')->column('id');
                $uids = $UserModel->where('name', 'like', '%' . $param['name'] . '%')->column('id');
                if (count($rating_scale_ids) > 0 || count($uids) > 0) {
                    if (count($rating_scale_ids) > 0) {
                        $where[] = ['rating_scale_id', 'in', $rating_scale_ids];
                    }
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    }
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['type_id'])) {
                $rating_scale_ids = $RatingScaleModel->where('type_id', '=', $param['type_id'])->column('id');
                if (count($rating_scale_ids) > 0) {
                    $where[] = ['rating_scale_id', 'in', $rating_scale_ids];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['answer_role'])) {
                $where[] = ['answer_role', '=', $param['answer_role']];
            }
            if (!empty($param['is_explain'])) {
                $where[] = ['is_explain', '=', $param['is_explain']];
            }
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                $where[] = ['is_warning', '=', $param['is_warning']];
            }
            if (isset($param['proxy_uid']) && strlen($param['proxy_uid']) > 0) {
                $where[] = ['proxy_uid', '=', $param['proxy_uid']];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['admin_del', '=', 0];
            if (!empty($param['id'])) {
                if (is_array($param['id'])) {
                    $where[] = ['id', 'in', $param['id']];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $UserService = new UserService($this->app);
            $DepartmentAdminModel = new DepartmentAdminModel();
            switch ($this->userData['role_mode']) {
                case 1:
                    $departmentIds = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                    $uids = $UserModel->where('department_id', 'in', $departmentIds)->column('id');
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['uid', '=', -1];
                    }
                    break;
                case 2:
                    $where[] = ['id', '=', -1];
                    break;
            }
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $query = $ProxyEvaluationResultModel->where($where);
            $data = $query
//                ->field('id,proxy_uid,uid,rating_scale_id,answer_role,total_score,time,result_read_auth,is_warning,warning_id,is_explain,is_special_group')
                ->with([
                    'user' => function ($query) {
                        $query->with([
                            'department' => function ($query) {
                                $query->with([
                                    'departmentAdmins' => function ($query) {
                                        $query->with(['userName']);
                                    }
                                ]);
                            },
                            'unitName'
                        ]);
                    },
                    'ratingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    },
                    'ProxyUser',
                    'RatingScaleFactorWarningModel'
                ])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            $departmentIds = array_column($data['data'], 'department_id');
            $NotDelDepartmentAll = $UserService->getDepartmentAffiliationAll2($this->userData['unit_id'], $departmentIds);
            foreach ($data['data'] as &$item) {
                $item['department_name'] = $NotDelDepartmentAll['department_data'][$item['department_id']]['all_name'] ?? '';
                $item['department_admins'] = $item['departmentAdmins'];
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 他人代测详情
     * @return bool|string
     */
    public function ProxyTestingReportInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getProxyTestingReportInfo($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }

    }

    /**
     * 删除他人代测报告
     * @return bool|string
     */
    public function ProxyTestingReportDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            if (is_array($id)) {
                $ProxyEvaluationResultModel->where('id', 'in', $id)->update([
                    'admin_del' => 1,
                ]);
            } else {
                $ProxyEvaluationResultModel->where('id', '=', $id)->update([
                    'admin_del' => 1,
                ]);
            }
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 修改自评测评报告查看权限
     * @return bool|string
     */
    public function selfResultReadAuth(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'result_read_auth|权限' => 'require'
            ]);
            $updateData = [
                'result_read_auth' => $param['result_read_auth']
            ];
            $result_read_auth = explode(',', $param['result_read_auth']);
            if (in_array(3, $result_read_auth)) {
                $updateData['is_new'] = 1;
            }
            $selfEvaluationResultModel = new selfEvaluationResultModel();
            if (is_array($param['id'])) {
                $selfEvaluationResultModel->where('id', 'in', $param['id'])->update($updateData);
            } else {
                $selfEvaluationResultModel->where('id', '=', $param['id'])->update($updateData);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 修改任务测评报告查看权限
     * @return bool|string
     */
    public function taskResultReadAuth(): bool|string
    {
        $this->mode->startTrans();
        try {
            $id = $this->request->param('id');
            $result_read_auth = $this->request->param('result_read_auth');
            $authData = explode(',', $result_read_auth);
            $is_auth = 0;
            foreach ($authData as $item) {
                if ($item == 3) $is_auth = 1;
            }
            $TaskUserResultModel = new TaskUserResultModel();
            $MessageModel = new MessageModel();
            $TaskModel = new TaskModel();
            $MessageData = [];
            if (is_array($id)) {
                if ($is_auth) {
                    foreach ($id as $item) {
                        $name = $TaskModel->where('id', '=', $item)->value('name');
                        $uids = $TaskUserResultModel->where('task_id', 'in', $item)->distinct(true)->column('uid');
                        foreach ($uids as $uid) {
                            $MessageData[] = [
                                'uid' => $uid,
                                'type' => 5,
                                'title' => '测评报告',
                                'content' => '您在' . $name . '测评任务中生成的测评报告，管理员已授权为可查看，请及时查看。',
                                'time' => time()
                            ];
                        }
                    }
                }
                $this->mode->where('id', 'in', $id)->update(['result_read_auth' => $result_read_auth]);
                $TaskUserResultModel->where('task_id', 'in', $id)->update(['result_read_auth' => $result_read_auth]);
            } else {
                $info = $this->mode->find($id);
                if ($is_auth) {
                    $uids = $TaskUserResultModel->where('task_id', '=', $id)->distinct(true)->column('uid');
                    foreach ($uids as $uid) {
                        $MessageData[] = [
                            'uid' => $uid,
                            'type' => 5,
                            'title' => '测评报告',
                            'content' => '您在' . $info['name'] . '测评任务中生成的测评报告，管理员已授权为可查看，请及时查看。',
                            'time' => time()
                        ];
                    }
                }
                $info->save(['result_read_auth' => $result_read_auth]);
                $TaskUserResultModel->where('task_id', '=', $id)->update(['result_read_auth' => $result_read_auth]);
            }
            $MessageModel->insertAll($MessageData, 200);
            $this->mode->commit();
            return success();
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 修改他人代测报告查看权限
     * @return bool|string
     */
    public function proxyResultReadAuth(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $result_read_auth = $this->request->param('result_read_auth');
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            if (is_array($id)) {
                $ProxyEvaluationResultModel->where('id', 'in', $id)->update(['result_read_auth' => $result_read_auth]);
            } else {
                $ProxyEvaluationResultModel->where('id', '=', $id)->update(['result_read_auth' => $result_read_auth]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警报告记录-修改查看权限
     * @return bool|string
     */
    public function WarningReportRecordReadAuth(): bool|string
    {
        $this->mode->startTrans();
        try {
            $id = $this->request->param('id');
            $result_read_auth = $this->request->param('result_read_auth');
            $WarningReportRecordModel = new WarningReportRecordModel();
            if (is_array($id)) {
                $data = $WarningReportRecordModel->where('id', 'in', $id)->field('id,source,result_id')->select()->toArray();
                $TaskIds = [];
                $SelfIds = [];
                $ProxyIds = [];
                foreach ($data as $item) {
                    switch ($item['source']) {
                        case 1:
                            $TaskIds[] = $item['result_id'];
                            break;
                        case 2:
                            $SelfIds[] = $item['result_id'];
                            break;
                        case 3:
                            $ProxyIds[] = $item['result_id'];
                            break;
                    }
                }
                if (count($TaskIds) > 0) {
                    $TaskUserResultModel = new TaskUserResultModel();
                    $TaskUserResultModel->whereIn('id', $TaskIds)->update(['result_read_auth' => $result_read_auth]);
                }
                if (count($SelfIds) > 0) {
                    $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                    $SelfEvaluationResultModel->whereIn('id', $SelfIds)->update(['result_read_auth' => $result_read_auth]);
                }
                if (count($ProxyIds) > 0) {
                    $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                    $ProxyEvaluationResultModel->whereIn('id', $ProxyIds)->update(['result_read_auth' => $result_read_auth]);
                }
            } else {
                $data = $WarningReportRecordModel->field('id,source,result_id')->find($id);
                switch ($data['source']) {
                    case 1:
                        $TaskUserResultModel = new TaskUserResultModel();
                        $TaskUserResultModel->where('id', '=', $data['result_id'])->update(['result_read_auth' => $result_read_auth]);
                        break;
                    case 2:
                        $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                        $SelfEvaluationResultModel->where('id', '=', $data['result_id'])->update(['result_read_auth' => $result_read_auth]);
                        break;
                    case 3:
                        $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                        $ProxyEvaluationResultModel->where('id', '=', $data['result_id'])->update(['result_read_auth' => $result_read_auth]);
                        break;
                }
            }
            $this->mode->commit();
            return success();
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警报告-搜索栏
     * @return bool|string
     */
    public function WarningSearch(): bool|string
    {
        try {
            $WarningReportRecordModel = new WarningReportRecordModel();
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $UserModel = new NotDelUserModel();
            $WarningReportList = $WarningReportRecordModel->where('unit_id', '=', $this->userData['unit_id'])->select()->toArray();
            $task_id = [];
            $self_id = [];
            $proxy_id = [];
            foreach ($WarningReportList as $item) {
                switch ($item['source']) {
                    case 1:
                        $task_id[] = $item['result_id'];
                        break;
                    case 2:
                        $self_id[] = $item['result_id'];
                        break;
                    case 3:
                        $proxy_id[] = $item['result_id'];
                        break;
                }
            }
            $uids = [];
            if (count($task_id)) {
                $uid = $TaskUserResultModel->where('id', 'in', $task_id)->column('uid');
                $uids = array_merge($uids, $uid);
            }
            if (count($self_id)) {
                $uid = $SelfEvaluationResultModel->where('id', 'in', $self_id)->column('uid');
                $uids = array_merge($uids, $uid);
            }
            if (count($proxy_id)) {
                $uid = $ProxyEvaluationResultModel->where('id', 'in', $proxy_id)->column('uid');
                $uids = array_merge($uids, $uid);
            }
            $where = [];
            if (count($uids)) {
                $uids = array_unique($uids);
                $where[] = ['id', 'in', $uids];
            } else {
                $where[] = ['id', '=', -1];
            }
            $department_id = $UserModel->where($where)->column('department_id');
            $department_id = array_unique($department_id);
            $DepartmentModel = new DepartmentModel();
            $data['department'] = $DepartmentModel->where('id', 'in', $department_id)->select()->toArray();
            $UserService = new UserService($this->app);
            $NotDelDepartmentAll = $UserService->getDepartmentAffiliationAll2($this->userData['unit_id'], $department_id);
            foreach ($data['department'] as &$item) {
                $item['name'] = $NotDelDepartmentAll['department_data'][$item['id']]['all_name'] ?? '';
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警报告记录
     * @return bool|string
     */
    public function WarningReportRecord(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $WarningWhere = [];
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $WarningReportRecordModel = new WarningReportRecordModel();
            $UserModel = new NotDelUserModel();
            $TaskModel = new TaskModel();
            $RatingScaleModel = new NotDelRatingScaleModel();
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (isset($param['answer_role']) && strlen($param['answer_role']) > 0) {
                $where[] = ['answer_role', '=', $param['answer_role']];
            }
            if (!empty($param['department_id'])) {
                $UserService = new UserService($this->app);
                $department_id = $UserService->getDepartmentAllLowerLevelIds($this->userData['unit_id'],[$param['department_id']]);
                $uid = $UserModel->where('department_id', 'in', $department_id)->column('id');
                if (!empty($uid)) {
                    $where[] = ['uid', 'in', $uid];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $hasNameResult = false; // 标记是否有匹配的搜索结果
            $hasNameResult2 = false; // 标记是否有匹配的搜索结果
            if (!empty($param['name'])) {
                $rating_scale_id = $RatingScaleModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                if (!empty($rating_scale_id)) {
                    $where[] = ['rating_scale_id', 'in', $rating_scale_id, 'or'];
                    $hasNameResult = true;
                    $hasNameResult2 = true;
                }
                $uid = $UserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                if (!empty($uid)) {
                    $where[] = ['uid', 'in', $uid, 'or'];
                    $hasNameResult = true;
                    $hasNameResult2 = true;
                }
            }
            if (!empty($where) || !empty($param['name'])) {
                $where[] = ['unit_id', '=', $this->userData['unit_id']];
                $where[] = ['is_warning', '=', 1];
                if (!empty($param['source'])) {
                    switch ($param['source']) {
                        case 1:
                            if (!empty($param['name'])){
                                $task_id = $TaskModel->where([
                                    ['unit_id', '=', $this->userData['unit_id']],
                                    ['name', 'like', '%' . $param['name'] . '%']
                                ])->column('id');
                                if (!empty($task_id)) {
                                    $where[] = ['task_id', 'in', $task_id,'or'];
                                    $hasNameResult = true;
                                }
                                if (!$hasNameResult) {
                                    $where[] = ['id', '=', -1];
                                }
                            }
                            $id = $TaskUserResultModel->where($where)->column('id');
                            $WarningWhere[] = ['result_id', 'in', $id];
                            break;
                        case 2:
                            if (!empty($param['name']) && !$hasNameResult){
                                $where[] = ['id', '=', -1];
                            }
                            $id = $SelfEvaluationResultModel->where($where)->column('id');
                            $WarningWhere[] = ['result_id', 'in', $id];
                            break;
                        case 3:
                            if (!empty($param['name']) && !$hasNameResult){
                                $where[] = ['id', '=', -1];
                            }
                            $id = $ProxyEvaluationResultModel->where($where)->column('id');
                            $WarningWhere[] = ['result_id', 'in', $id];
                            break;
                    }
                } else {
                    $taskWhere = $where;
                    if (!empty($param['name'])){
                        $task_id = $TaskModel->where([
                            ['unit_id', '=', $this->userData['unit_id']],
                            ['name', 'like', '%' . $param['name'] . '%']
                        ])->column('id');
                        if (!empty($task_id)) {
                            $taskWhere[] = ['task_id', 'in', $task_id, 'or'];
                            $hasNameResult2 = true;
                        }
                        if (!$hasNameResult){
                            $where[] = ['id', '=', -1];
                        }
                        if (!$hasNameResult2){
                            $taskWhere[] = ['id', '=', -1];
                        }
                    }
                    $id = $TaskUserResultModel->where($taskWhere)->column('id');
                    $ids = $WarningReportRecordModel->where([
                        ['result_id', 'in', $id],
                        ['source', '=', 1],
                    ])->column('id');
                    $id2 = $SelfEvaluationResultModel->where($where)->column('id');
                    $ids2 = $WarningReportRecordModel->where([
                        ['result_id', 'in', $id2],
                        ['source', '=', 2],
                    ])->column('id');
                    $id3 = $ProxyEvaluationResultModel->where($where)->column('id');
                    $ids3 = $WarningReportRecordModel->where([
                        ['result_id', 'in', $id3],
                        ['source', '=', 3],
                    ])->column('id');
                    $ids = array_unique(array_merge($ids, $ids2, $ids3));
                    $WarningWhere[] = ['id', 'in', $ids];
                }
            }
            if (!empty($param['source'])) {
                $WarningWhere[] = ['source', '=', $param['source']];
            }
            $WarningWhere[] = ['unit_id', '=', $this->userData['unit_id']];
            $UserService = new UserService($this->app);
            $DepartmentAdminModel = new DepartmentAdminModel();
            switch ($this->userData['role_mode']) {
                case 1:
                    $departmentIds = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                    $uids = $UserModel->where('department_id', 'in', $departmentIds)->column('id');
                    if (count($uids) > 0) {
                        $WarningWhere[] = ['uid', 'in', $uids];
                    } else {
                        $WarningWhere[] = ['uid', '=', -1];
                    }
                    break;
                case 2:
                    $WarningWhere[] = ['id', '=', -1];
                    break;
            }
            if (!empty($param['id'])) {
                if (is_array($param['id'])) {
                    $WarningWhere[] = ['id', 'in', $param['id']];
                } else {
                    $WarningWhere[] = ['id', '=', -1];
                }
            }
            $query = $WarningReportRecordModel->where($WarningWhere);
            $data = $query->order('id desc')->paginate($param['pageSize'])->toArray();
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $NotDelDepartmentAll = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
            foreach ($data['data'] as &$item) {
                switch ($item['source']) {
                    case 1:
                        $item['source_name'] = '任务测评';
                        $info = $TaskUserResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'task',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    case 2:
                        $item['source_name'] = '自我测评';
                        $info = $SelfEvaluationResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    case 3:
                        $item['source_name'] = '他人代测';
                        $info = $ProxyEvaluationResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    default:
                        break;
                }
                if (!isset($info)) {
                    continue;
                }
                $item = [
                    'id' => $item['id'],
                    'user_name' => $info['user_name'],
                    'user_avatar' => $info['user_avatar'],
                    'age' => $info['age'],
                    'sex' => $info['sex'],
                    'warning_name' => $info['warning_name'],
                    'total_score' => $info['total_score'],
                    'task_name' => $info['task_name'] ?? '--',
                    'is_explain' => $info['is_explain'],
                    'source' => $item['source_name'],
                    'answer_role' => $info['answer_role'],
                    'rating_scale_name' => $info['rating_scale_name'],
                    'rating_scale_type_name' => $info['rating_scale_type_name'],
                    'unit_name' => $info['unit_name'],
                    'department_name' => $NotDelDepartmentAll[$info['department_id']]['all_name'] ?? '--',
                    'ascription_name' => $NotDelDepartmentAll[$info['department_id']]['ascription_name'] ?? '--',
                    'department_admins' => $info['departmentAdmins'] ?? [],
                    'result_read_auth' => $info['result_read_auth'],
                    'time' => $info['time'],
                    'student_status' => $info['student_status'],
                    'username' => $info['username'],
                    'number' => $info['uid']
                ];
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 预警报告记录-删除
     * @return bool|string
     */
    public function WarningReportRecordDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $WarningReportRecordModel = new WarningReportRecordModel();
            if (is_array($id)) {
                $WarningReportRecordModel->where('id', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            } else {
                $WarningReportRecordModel->where('id', '=', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警报告记录-详情
     * @return bool|string
     */
    public function WarningReportRecordInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $WarningReportRecordModel = new WarningReportRecordModel();
            $info = $WarningReportRecordModel->find($id);
            $ReportService = new ReportService($this->app);
            switch ($info['source']) {
                case 1:
                    $data = $ReportService->getTaskReportInfo($info['result_id']);
                    $TaskModel = new TaskModel();
                    $task = $TaskModel->with([
                        'userName'
                    ])->find($data['task_id']);
                    $data['task_name'] = $task['name'];
                    $data['task_publisher'] = $task['user_name'];
                    $data['task_user_count'] = $task['user_count'];
                    $data['task_user_complete_num'] = $task['user_complete_num'];
                    $data['task_user_complete_rate'] = $task['user_complete_rate'];
                    $data['task_start_time'] = $task['start_time'];
                    $data['task_end_time'] = $task['end_time'];
                    $data['task_warning_num'] = $task['warning_num'];
                    $data['task_price'] = $task['price'];
                    break;
                case 2:
                    $data = $ReportService->getSelfReportInfo($info['result_id']);
                    break;
                case 3:
                    $data = $ReportService->getProxyReportInfo($info['result_id']);
                    break;
                default:
                    throw new \Exception('参数错误！');
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 申请解读记录
     * @return bool|string
     */
    public function InterpretationRecord(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $InterpretationRecordModel = new InterpretationRecordModel();
            $RatingScaleModel = new NotDelRatingScaleModel();
            $TaskModel = new TaskModel();
            $DepartmentAdminModel = new NotDepartmentAdminModel();
            $UserModel = new NotDelUserModel();
            if (!empty($param['is_explain'])) {
                $where[] = ['is_explain', '=', $param['is_explain']];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['explain_uid'])) {
                $where[] = ['explain_uid', '=', $param['explain_uid']];
            }
            $ResultWhere = [];
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                $ResultWhere[] = ['is_warning', '=', $param['is_warning']];
            }
            if (!empty($param['admin'])) {
                $department_id = $DepartmentAdminModel->where('uid', '=', $param['admin'])->column('department_id');
                $uid = [];
                if (count($department_id) > 0) {
                    $uid = $UserModel->where('department_id', 'in', $department_id)->column('id');
                }
                if (count($uid) > 0) {
                    $ResultWhere[] = ['uid', 'in', $uid];
                } else {
                    $ResultWhere[] = ['id', '=', -1];
                }
            }
            if (!empty($param['name'])) {
                $task_id = $TaskModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                $rating_scale_id = $RatingScaleModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                $uid = $UserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                if (!empty($param['source'])) {
                    $where[] = ['source', '=', $param['source']];
                    $ResultWhere[] = ['unit_id', '=', $this->userData['unit_id']];
                    $ResultWhere[] = ['is_explain', '>', 1];
                    switch ($param['source']) {
                        case 1:
                            //任务
                            if (!empty($task_id) || !empty($rating_scale_id) || !empty($uid)) {
                                if (!empty($task_id)) {
                                    $ResultWhere[] = ['task_id', 'in', $task_id, 'or'];
                                }
                                if (!empty($rating_scale_id)) {
                                    $ResultWhere[] = ['rating_scale_id', 'in', $rating_scale_id, 'or'];
                                }
                                if (!empty($uid)) {
                                    $ResultWhere[] = ['uid', 'in', $uid, 'or'];
                                }
                            } else {
                                break;
                            }
                            $taskQuery = $TaskUserResultModel->where($ResultWhere);
                            $result_id = $taskQuery->column('id');
                            break;
                        case 2:
                            //自我
                            if (!empty($rating_scale_id) || !empty($uid)) {
                                if (!empty($rating_scale_id)) {
                                    $ResultWhere[] = ['rating_scale_id', 'in', $rating_scale_id, 'or'];
                                }
                                if (!empty($uid)) {
                                    $ResultWhere[] = ['uid', 'in', $uid, 'or'];
                                }
                            } else {
                                break;
                            }
                            $selfQuery = $SelfEvaluationResultModel->where($ResultWhere);
                            $result_id = $selfQuery->column('id');
                            break;
                        case 3:
                            //他人
                            if (!empty($rating_scale_id) || !empty($uid)) {
                                if (!empty($rating_scale_id)) {
                                    $ResultWhere[] = ['rating_scale_id', 'in', $rating_scale_id, 'or'];
                                }
                                if (!empty($uid)) {
                                    $ResultWhere[] = ['uid', 'in', $uid, 'or'];
                                }
                            } else {
                                break;
                            }
                            $proxyQuery = $ProxyEvaluationResultModel->where($ResultWhere);
                            $result_id = $proxyQuery->column('id');
                            break;
                    }
                    if (!empty($result_id)) {
                        $where[] = ['result_id', 'in', $result_id];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                } else {
                    $ResultWhere[] = ['unit_id', '=', $this->userData['unit_id']];
                    $ResultWhere[] = ['is_explain', '>', 1];

                    $taskResultWhere = $ResultWhere;
                    $selfResultWhere = $ResultWhere;
                    $proxyResultWhere = $ResultWhere;

                    //任务
                    if (!empty($task_id) || !empty($rating_scale_id) || !empty($uid)) {
                        if (!empty($task_id)) {
                            $taskResultWhere[] = ['task_id', 'in', $task_id, 'or'];
                        }
                        if (!empty($rating_scale_id)) {
                            $taskResultWhere[] = ['rating_scale_id', 'in', $rating_scale_id, 'or'];
                        }
                        if (!empty($uid)) {
                            $taskResultWhere[] = ['uid', 'in', $uid, 'or'];
                        }
                        $taskQuery = $TaskUserResultModel->where($taskResultWhere);
                        $task_result_id = $taskQuery->column('id');
                    } else {
                        $task_result_id = [];
                    }

                    //自我
                    if (!empty($rating_scale_id) || !empty($uid)) {
                        if (!empty($rating_scale_id)) {
                            $selfResultWhere[] = ['rating_scale_id', 'in', $rating_scale_id, 'or'];
                        }
                        if (!empty($uid)) {
                            $selfResultWhere[] = ['uid', 'in', $uid, 'or'];
                        }
                        $selfQuery = $SelfEvaluationResultModel->where($selfResultWhere);
                        $self_result_id = $selfQuery->column('id');
                    } else {
                        $self_result_id = [];
                    }
                    //他人
                    if (!empty($rating_scale_id) || !empty($uid)) {
                        if (!empty($rating_scale_id)) {
                            $proxyResultWhere[] = ['rating_scale_id', 'in', $rating_scale_id, 'or'];
                        }
                        if (!empty($uid)) {
                            $proxyResultWhere[] = ['uid', 'in', $uid, 'or'];
                        }
                        $proxyQuery = $ProxyEvaluationResultModel->where($proxyResultWhere);
                        $proxy_result_id = $proxyQuery->column('id');
                    } else {
                        $proxy_result_id = [];
                    }
                    $ids = array_unique(array_merge($task_result_id, $self_result_id, $proxy_result_id));
                    if (!empty($ids)) {
                        $where[] = ['result_id', 'in', $ids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
            } else {
                if (!empty($param['source'])) {
                    $where[] = ['source', '=', $param['source']];
                    $ResultWhere[] = ['unit_id', '=', $this->userData['unit_id']];
                    $ResultWhere[] = ['is_explain', '>', 1];
                    switch ($param['source']) {
                        case 1:
                            //任务
                            $taskQuery = $TaskUserResultModel->where($ResultWhere);
                            $result_id = $taskQuery->column('id');
                            break;
                        case 2:
                            //自我
                            $selfQuery = $SelfEvaluationResultModel->where($ResultWhere);
                            $result_id = $selfQuery->column('id');
                            break;
                        case 3:
                            //他人
                            $proxyQuery = $ProxyEvaluationResultModel->where($ResultWhere);
                            $result_id = $proxyQuery->column('id');
                            break;
                    }
                    if (!empty($result_id)) {
                        $where[] = ['result_id', 'in', $result_id];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                } else {
                    if (!empty($ResultWhere)) {
                        $ResultWhere[] = ['unit_id', '=', $this->userData['unit_id']];
                        $ResultWhere[] = ['is_explain', '>', 1];
                        //任务
                        $taskQuery = $TaskUserResultModel->where($ResultWhere);
                        $task_result_id = $taskQuery->column('id');
                        //自我
                        $selfQuery = $SelfEvaluationResultModel->where($ResultWhere);
                        $self_result_id = $selfQuery->column('id');
                        //他人
                        $proxyQuery = $ProxyEvaluationResultModel->where($ResultWhere);
                        $proxy_result_id = $proxyQuery->column('id');
                        $ids = array_unique(array_merge($task_result_id, $self_result_id, $proxy_result_id));
                        if (!empty($ids)) {
                            $where[] = ['result_id', 'in', $ids];
                        } else {
                            $where[] = ['id', '=', -1];
                        }
                    }
                }
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $UserService = new UserService($this->app);
            switch ($this->userData['role_mode']) {
                case 1:
                    $departmentIds = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                    $uids = $UserModel->where('department_id', 'in', $departmentIds)->column('id');
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['uid', '=', -1];
                    }
                    break;
                case 2:
                    $where[] = ['id', '=', -1];
                    break;
            }
            $query = $InterpretationRecordModel->where($where);
            $data = $query->order('id desc')->paginate($param['pageSize'])->toArray();
            $NotDelDepartmentAll = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
            foreach ($data['data'] as &$item) {
                switch ($item['source']) {
                    case 1:
                        $item['source_name'] = '任务测评';
                        $info = $TaskUserResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'task',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
//                        if (!$info) throw new \Exception('有报告被删除');
                        break;
                    case 2:
                        $item['source_name'] = '自我测评';
                        $info = $SelfEvaluationResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
//                        if (!$info) throw new \Exception('有报告被删除');
                        break;
                    case 3:
                        $item['source_name'] = '他人代测';
                        $info = $ProxyEvaluationResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
//                        if (!$info) throw new \Exception('有报告被删除');
                        break;
                    default:
                        break;
                }
                if (!isset($info)) {
                    continue;
                }
                $item = [
                    'id' => $item['id'],
                    'rating_scale_name' => $info['rating_scale_name'],
                    'rating_scale_cover' => $info['rating_scale_cover'],
                    'interpretation_fee' => $info['interpretation_fee'],
                    'is_explain' => $info['is_explain'],
                    'source' => $item['source_name'] ?? '--',
                    'task_name' => $info['task_name'] ?? '--',
                    'user_name' => $info['user_name'],
                    'sex' => $info['sex'],
                    'age' => $info['age'],
                    'unit_name' => $info['unit_name'],
                    'department_name' => $NotDelDepartmentAll[$info['department_id']]['all_name'] ?? '',
                    'department_admins' => $info['departmentAdmins'] ?? [],
                    'result_read_auth' => $info['result_read_auth'],
                    'time' => $item['time'],
                    'student_status' => $info['student_status'],
                    'username' => $info['username'],
                    'user_number' => $info['user_number'],
                    'rating_scale_type_name' => $info['rating_scale_type_name'],
                    'total_score' => $info['total_score'],
                    'is_warning' => $info['is_warning'],
                    'warning_name' => $info['warning_name'],
                    'answer_role' => $info['answer_role'],
                ];
            }
            $data['ids'] = $query->column('id');
            return success(['data' => $data, 'total' => $query->where('is_explain', 'in', [1, 2])->count()]);
        } catch (\Exception $e) {
            return error($e->getMessage() . $e->getLine());
        }
    }

    /**
     * 申请解读记录-删除
     * @return bool|string
     */
    public function InterpretationRecordDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $InterpretationRecordModel = new InterpretationRecordModel();
            if (is_array($id)) {
                $InterpretationRecordModel->where('id', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            } else {
                $InterpretationRecordModel->where('id', '=', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 申请解读记录-详情
     * @return bool|string
     */
    public function InterpretationRecordInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $InterpretationRecordModel = new InterpretationRecordModel();
            $info = $InterpretationRecordModel->find($id);
            $ReportService = new ReportService($this->app);
            switch ($info['source']) {
                case 1:
                    $data = $ReportService->getTaskReportInfo($info['result_id']);
                    $TaskModel = new TaskModel();
                    $task = $TaskModel->with([
                        'userName'
                    ])->find($data['task_id']);
                    $data['task_name'] = $task['name'];
                    $data['task_publisher'] = $task['user_name'];
                    $data['task_user_count'] = $task['user_count'];
                    $data['task_user_complete_rate'] = $task['user_complete_rate'];
                    $data['task_start_time'] = $task['start_time'];
                    $data['task_end_time'] = $task['end_time'];
                    $data['task_warning_num'] = $task['warning_num'];
                    $data['task_price'] = $task['price'];
                    break;
                case 2:
                    $data = $ReportService->getSelfReportInfo($info['result_id']);
                    break;
                case 3:
                    $data = $ReportService->getProxyReportInfo($info['result_id']);
                    break;
                default:
                    throw new \Exception('参数错误！');
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 测评解读
     * @return bool|string
     */
    public function ExplainUpdate(): bool|string
    {
        $InterpretationRecordModel = new InterpretationRecordModel();
        $InterpretationRecordModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'explain|解读内容' => 'require'
            ]);
            $info = $InterpretationRecordModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            switch ($info->source) {
                case 1:
                    $TaskUserResultModel = new TaskUserResultModel();
                    $TaskUserResultModel->where('id', '=', $info->result_id)->update([
                        'explain' => $param['explain'],
                        'is_explain' => 3,
                        'explain_time' => time(),
                        'explain_uid' => $this->userData['id']
                    ]);
                    break;
                case 2:
                    $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                    $SelfEvaluationResultModel->where('id', '=', $info->result_id)->update([
                        'explain' => $param['explain'],
                        'is_explain' => 3,
                        'explain_time' => time(),
                        'explain_uid' => $this->userData['id'],
                        'is_new' => 1
                    ]);
                    break;
                case 3:
                    $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                    $ProxyEvaluationResultModel->where('id', '=', $info->result_id)->update([
                        'explain' => $param['explain'],
                        'is_explain' => 3,
                        'explain_time' => time(),
                        'explain_uid' => $this->userData['id']
                    ]);
                    break;
                default:
                    throw new \Exception('参数错误！');
            }
            $info->save([
                'is_explain' => 3,
                'explain_uid' => $this->userData['id'],
                'up_time' => time()
            ]);
            $MessageModel = new MessageModel();
            $MessageModel->insert([
                'uid' => $info['uid'],
                'type' => 7,
                'content' => '您于' . date('Y-m-d', $info['time']) . '日期' . date('H:i:s', $info['time']) . '时间提交的解读申请，已由管理员' . $this->userData['name'] . '完成解读，请及时查看。',
                'time' => time()
            ]);
            $InterpretationRecordModel->commit();
            return success();
        } catch (\Exception $e) {
            $InterpretationRecordModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评解读详情
     * @return bool|string
     */
    public function TaskExplainInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserResultModel = new TaskUserResultModel();
            $data = $TaskUserResultModel->field('id,uid,explain_uid,rating_scale_id,interpretation_fee,explain_time,explain')->with([
                'ExplainUserName', 'UserName', 'RatingScaleName'
            ])->find($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评解读详情
     * @return bool|string
     */
    public function SelfExplainInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $data = $SelfEvaluationResultModel->field('id,uid,explain_uid,rating_scale_id,interpretation_fee,explain_time,explain')->with([
                'ExplainUserName', 'UserName', 'RatingScaleName'
            ])->find($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 他人代测解读详情
     * @return bool|string
     */
    public function ProxyExplainInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $data = $ProxyEvaluationResultModel->field('id,uid,explain_uid,rating_scale_id,interpretation_fee,explain_time,explain')->with([
                'ExplainUserName', 'UserName', 'RatingScaleName'
            ])->find($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告-删除单个报告
     * @return bool|string
     */
    public function TaskReportOneDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserResultModel = new TaskUserResultModel();
            $info = $TaskUserResultModel->find($id);
            $TaskModel = new TaskModel();
            $uid = $TaskModel->where('id', '=', $info->task_id)->value('uid');
            if ($uid != $this->userData['id']) throw new \Exception('任务发布人才能删除！');
            $info->admin_del = 1;
            $info->save();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 任务测评团体报告
     * @return bool|string
     */
    public function TaskGroupReport(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $department_id = $this->request->param('department_id');
            $DepartmentModel = new NotDelDepartmentModel();
            $data = $DepartmentModel->field('id,pid')->where('unit_id', '=', $this->userData['unit_id'])->select()->toArray();
            $DepartmentIds = getAllSubcategories($data, $department_id);
            $DepartmentIds = array_column($DepartmentIds, 'id');
            $DepartmentIds[] = (int)$department_id;
            $UserModel = new NotDelUserModel();
            $uids = $UserModel->where('department_id', 'in', $DepartmentIds)->column('id');
            $GroupReportExportService = new GroupReportExportService($this->app);
            return $GroupReportExportService->TaskGroupReportExportData($task_id, $rating_scale_id, $uids);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }

    }

    /**
     * 获取他人代测报告
     * @return bool|string
     */
    public function getProxyReportInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getProxyReportInfo($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取自我测评报告
     * @return bool|string
     */
    public function getSelfReportInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getSelfReportInfo($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我报告导出（word）
     * @return bool|string
     */
    public function SelfReportExport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $unit_id = $this->request->param('unit_id');
            $ConfigModel = new ConfigModel();
            if (empty($unit_id)) {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            } else {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $unit_id],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            }
            $config = json_decode($config, true);
            if ($config['export_format'] == 1) {
                if (empty($config['version_report'])) {
                    $type = 'pdf';
                } else {
                    $type = 'concise_pdf';
                }
            } else {
                if (empty($config['version_report'])) {
                    $type = 'word';
                } else {
                    $type = 'concise_word';
                }
            }
            $where[] = ['id', 'in', $id];
            $ReportExportService = new ReportExportService($this->app);
            switch (env("UPLOAD_TYPE")) {
                case 'local':
                    if (!$ReportExportService->pack2($where, 'Self', $type))
                        throw new \Exception($ReportExportService->message);
                    break;
                case 'oss':
                    if (!$ReportExportService->streamCompress($where, 'Self', $type))
                        throw new \Exception($ReportExportService->message);
                    break;
            }
            return success($ReportExportService->data['zipFileName']);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 他人代测报告导出（word）
     * @return bool|string
     */
    public function ProxyReportExport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $unit_id = $this->request->param('unit_id');
            $ConfigModel = new ConfigModel();
            if (empty($unit_id)) {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            } else {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $unit_id],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            }
            $config = json_decode($config, true);
            if ($config['export_format'] == 1) {
                if (empty($config['version_report'])) {
                    $type = 'pdf';
                } else {
                    $type = 'concise_pdf';
                }
            } else {
                if (empty($config['version_report'])) {
                    $type = 'word';
                } else {
                    $type = 'concise_word';
                }
            }
            $where[] = ['id', 'in', $id];
            $ReportExportService = new ReportExportService($this->app);
            switch (env("UPLOAD_TYPE")) {
                case 'local':
                    if (!$ReportExportService->pack2($where, 'Proxy', $type))
                        throw new \Exception($ReportExportService->message);
                    break;
                case 'oss':
                    if (!$ReportExportService->streamCompress($where, 'Proxy', $type))
                        throw new \Exception($ReportExportService->message);
                    break;
            }
            return success($ReportExportService->data['zipFileName']);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警报告导出（word）
     * @return bool|string
     */
    public function WarningReportExport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $WarningReportRecordModel = new WarningReportRecordModel();
            $data = $WarningReportRecordModel->where('id', 'in', $id)->field('id,source,result_id')->select()->toArray();
            $id1 = [];
            $id2 = [];
            $id3 = [];
            $ConfigModel = new ConfigModel();
            $unit_id = $this->request->param('unit_id');
            if (empty($unit_id)) {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            } else {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $unit_id],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            }
            $config = json_decode($config, true);
            if ($config['export_format'] == 1) {
                if (empty($config['version_report'])) {
                    $fileType = 'pdf';
                } else {
                    $fileType = 'concise_pdf';
                }
            } else {
                if (empty($config['version_report'])) {
                    $fileType = 'word';
                } else {
                    $fileType = 'concise_word';
                }
            }
            foreach ($data as $item) {
                switch ($item['source']) {
                    case 1:
                        $id1[] = $item['result_id'];
                        break;
                    case 2:
                        $id2[] = $item['result_id'];
                        break;
                    case 3:
                        $id3[] = $item['result_id'];
                }
            }
            $fileList = [];
            if (!empty($id1)) {
                $TaskUserResultModel = new TaskUserResultModel();
                $data1 = $TaskUserResultModel
                    ->where('id', 'in', $id1)
                    ->field('id,word,pdf,concise_pdf,concise_word,uid')->with([
                        'UserName'
                    ])->select()->toArray();
                foreach ($data1 as $item) {
                    if (empty($item[$fileType])) continue;
                    $fileList[] = [
                        'file' => $item[$fileType],
                        'user_name' => $item['user_name'],
                    ];
                }
            }
            if (!empty($id2)) {
                $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                $data2 = $SelfEvaluationResultModel
                    ->where('id', 'in', $id2)
                    ->field('id,word,pdf,concise_pdf,concise_word,uid')->with([
                        'UserName'
                    ])->select()->toArray();
                foreach ($data2 as $item) {
                    if (empty($item[$fileType])) continue;
                    $fileList[] = [
                        'file' => $item[$fileType],
                        'user_name' => $item['user_name'],
                    ];
                }
            }
            if (!empty($id3)) {
                $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                $data3 = $ProxyEvaluationResultModel
                    ->where('id', 'in', $id3)
                    ->field('id,word,pdf,concise_pdf,concise_word,uid')->with([
                        'UserName'
                    ])->select()->toArray();
                foreach ($data3 as $item) {
                    if (empty($item[$fileType])) continue;
                    $fileList[] = [
                        'file' => $item[$fileType],
                        'user_name' => $item['user_name'],
                    ];
                }
            }
            if (empty($fileList)) throw new \Exception('没有数据可导出！');
            $ext = '.zip';
            $save_name = '/export/pack' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
            $file_path = dirname('./public' . $save_name . $ext);
            folder_build($file_path);
            $zip = new ZipArchive();
            if ($zip->open('./public' . $save_name . $ext, ZipArchive::CREATE) !== TRUE) {
                throw new \Exception('无法创建ZIP文件');
            }

            switch (env("UPLOAD_TYPE")) {
                case 'local':
                    foreach ($fileList as $item) {
                        if (!file_exists('.' . $item['file'])) continue;
                        $zip->addFile('.' . $item['file'], $item['user_name'] . basename('.' . $item['file']));
                    }
                    break;
                case 'oss':
                    // 初始化OSS客户端
                    $config = config('app.oss');
                    // 获取AK和SK信息
                    $accessKeyId = $config['access_key_id'];
                    $accessKeySecret = $config['access_key_secret'];
                    $provider = new StaticCredentialsProvider($accessKeyId, $accessKeySecret);
                    $endpoint = $config['upload_url'];
                    $ossConfig = array(
                        "provider" => $provider,
                        "endpoint" => $endpoint,
                        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
                        "region" => "cn-beijing"
                    );
                    $ossClient = new OssClient($ossConfig);
                    $wg = new WaitGroup();
                    $pool = new Channel(10); // 限制最大并发为10
                    $chunks = array_chunk($fileList, 30); // 每批30条
                    foreach ($chunks as $chunk) {
                        foreach ($chunk as $item) {
                            if (empty($item['file'])) {
                                continue;
                            }
                            $wg->add(); // 添加任务计数
                            go(function () use ($pool, $ossClient, $config, $item, $zip, $wg) {
                                try {
                                    $pool->push(true); // 占用一个协程槽位
                                    // 流式获取OSS文件内容
                                    $file = str_replace($config['static_url'] . '/', '', $item['file']);
                                    $stream = $ossClient->getObject(
                                        $config['bucket_name'],
                                        $file
                                    );
                                    // 直接写入ZIP不落盘
                                    $zip->addFromString($item['user_name'] . basename($file), $stream);
                                } catch (\Throwable $e) {
                                    Log::channel('go')->error('压缩文件: ' . $e->getMessage());
                                } finally {
                                    $pool->pop(); // 释放协程槽位
                                    $wg->done();
                                }
                            });
                        }
                        $wg->wait(); // 每批完成后等待
                    }
            }

            $zip->close();
            return match (env("UPLOAD_TYPE")) {
                'local' => success('./public' . $save_name . $ext),
                'oss' => success(oss('./public' . $save_name . $ext, $ext)),
                default => throw new \Exception('系统配置错误！'),
            };
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评团体报告导出数据
     * @return bool|string
     */
    public function TaskGroupReportExportData(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $uid = $this->request->param('uid');
            $GroupReportExportService = new GroupReportExportService($this->app);
            return $GroupReportExportService->TaskGroupReportExportData($task_id, $rating_scale_id, $uid);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警报告解读详情
     * @return bool|string
     */
    public function WarningReportExplainInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $WarningReportRecordModel = new WarningReportRecordModel();
            $data = $WarningReportRecordModel->find($id);
            $model = match ($data['source']) {
                1 => new TaskUserResultModel(),
                2 => new SelfEvaluationResultModel(),
                3 => new ProxyEvaluationResultModel(),
            };
            $info = $model->find($data['result_id']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务单个量表的所有单人报告导出（word/pdf）
     * @return bool|string
     */
    public function TaskReportExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'uid|用户' => 'require'
            ]);
            $ConfigModel = new ConfigModel();
            if (empty($param['unit_id'])) {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            } else {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $param['unit_id']],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            }
            $config = json_decode($config, true);
            if ($config['export_format'] == 1) {
                if (empty($config['version_report'])) {
                    $type = 'pdf';
                } else {
                    $type = 'concise_pdf';
                }
            } else {
                if (empty($config['version_report'])) {
                    $type = 'word';
                } else {
                    $type = 'concise_word';
                }
            }
            $where[] = ['task_id', '=', $param['task_id']];
            $where[] = ['rating_scale_id', '=', $param['rating_scale_id']];
            $where[] = ['uid','in',$param['uid']];
            $ReportExportService = new ReportExportService($this->app);
            switch (env("UPLOAD_TYPE")) {
                case 'local':
                    if (!$ReportExportService->pack2($where, 'Task', $type))
                        throw new \Exception($ReportExportService->message);
                    break;
                case 'oss':
                    if (!$ReportExportService->streamCompress($where, 'Task', $type))
                        throw new \Exception($ReportExportService->message);
                    break;
            }
            return success($ReportExportService->data['zipFileName']);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 导出表格数据
     * @return bool|string
     */
    public function exportData(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
            ]);
            $where[] = ['task_id', '=', $param['task_id']];
            $where[] = ['rating_scale_id', '=', $param['rating_scale_id']];
            $TaskService = new TaskService($this->app);
            $data = $TaskService->exportData($this->userData['unit_id'], $where);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 导出报告（根据配置导对应的报告）
     * @return bool|string
     */
    public function exportReport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'channel|报告类型' => 'require'
            ]);
            $ConfigModel = new ConfigModel();
            if (empty($param['unit_id'])) {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            } else {
                $config = $ConfigModel->where([
                    ['unit_id', '=', $param['unit_id']],
                    ['key', '=', 'evaluation_report']
                ])->value('value');
            }
            $config = json_decode($config, true);
            if ($config['export_format'] == 1) {
                if (empty($config['version_report'])) {
                    $type = 'pdf';
                } else {
                    $type = 'concise_pdf';
                }
            } else {
                if (empty($config['version_report'])) {
                    $type = 'word';
                } else {
                    $type = 'concise_word';
                }
            }
            $where[] = ['id', 'in', $param['id']];
            $ReportExportService = new ReportExportService($this->app);
            switch (env("UPLOAD_TYPE")) {
                case 'local':
                    if (!$ReportExportService->pack2($where, $param['channel'], $type))
                        throw new \Exception($ReportExportService->message);
                    break;
                case 'oss':
                    if (!$ReportExportService->streamCompress($where, $param['channel'], $type))
                        throw new \Exception($ReportExportService->message);
                    break;
            }
            return success($ReportExportService->data['zipFileName']);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    public function warningUserSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require'
            ]);
            $TaskUserResultModel = new TaskUserResultModel();
            $uid = $TaskUserResultModel->where([
                ['task_id', '=', $param['task_id']],
                ['rating_scale_id', '=', $param['rating_scale_id']]
            ])->column('uid');
            $UserModel = new UserModel();
            $department_id = $UserModel->where('id', 'in', $uid)->column('department_id');
            if (!empty($department_id)) {
                $UserService = new UserService($this->app);
                $DepartmentIds = $UserService->getDepartmentAllIds($this->userData['unit_id'], $department_id);
                $where[] = ['id', 'in', $DepartmentIds];
            } else {
                $where[] = ['id', '=', -1];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->where($where)
                ->with([
                    'users' => function ($query) use ($uid) {
                        $query->where('id', 'in', $uid)->field('id,department_id,name,sex,age,user_number');
                    }
                ])->select()->toArray();
            if (!empty($data)) {
                $data2[] = [
                    'id' => 0,
                    'name' => $this->userData['unit']['name'] ?? '',
                    'child' => buildTree($data),
                    'users' => []
                ];
            } else {
                $data2 = [];
            }
            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 预警用户再测
     * @return bool|string
     */
    public function warningUser(): bool|string
    {
        $TaskModel = new TaskModel();
        $TaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'name|任务名称' => 'require',
                'is_time|是否限时' => 'require',
            ]);
            $TaskUserResultModel = new TaskUserResultModel();
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskUserModel = new TaskUserModel();
            $taskInfo = $TaskModel->find($param['id']);
            if (!$taskInfo) throw new \Exception('参数错误！');
            $taskData = $taskInfo->toArray();

            $uid = $TaskUserResultModel->where([
                ['task_id','=',$param['id']],
                ['is_warning','=',1],
                ['rating_scale_id','=',$param['rating_scale_id']]
            ])->distinct(true)->column('uid');

            $taskData['uid'] = $this->userData['id'];
            $taskData['name'] = $param['name'];
            $taskData['is_time'] = $param['is_time'];
            $taskData['rating_scale_count'] = 1;
            $taskData['user_count'] = count($uid);
            $taskData['user_complete_num'] = 0;
            $taskData['user_complete_rate'] = '0.00';
            $taskData['warning_num'] = 0;
            $taskData['time'] = $time = time();
            $taskData['status'] = 1;

            if (!empty($taskData['is_time']) && $taskData['is_time'] == 1) {
                if (empty($taskData['start_time']) || empty($taskData['end_time'])) throw new \Exception('请填写开始和结束时间！');
                if ($taskData['start_time'] <= $taskData['time'] && $taskData['end_time'] >= $taskData['time']) {
                    //在任务时间内将任务设为进行中
                    $taskData['status'] = 2;
                }
            } else {
                $taskData['status'] = 2;
            }
            unset($taskData['id']);
            $taskId = $TaskModel->insertGetId($taskData);

            //任务量表
            $TaskRatingScaleModel->insert([
                'task_id' => $taskId,
                'rating_scale_id' => $param['rating_scale_id'],
                'time' => $time
            ]);
            //任务用户
            foreach ($uid as $v) {
                $task_user[] = [
                    'task_id' => $taskId,
                    'rating_scale_id' => $param['rating_scale_id'],
                    'uid' => $v,
                    'time' => $time
                ];
            }
            if (!empty($task_user)) {
                $TaskUserModel->insertAll($task_user, 200);
            }
            $TaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $TaskModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 发布任务（高校）
     * @return false|string
     */
    public function releaseTask2(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'name|任务名称' => 'require',
                'type|量表类型' => 'require',
                'is_time|是否限时' => 'require',
                'rating_scale|量表' => 'require',
                'code_type|任务类型' => 'require'
            ]);
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskUserModel = new TaskUserModel();
            $TaskContinuousEvaluation = new TaskContinuousEvaluationModel();
            $ConfigModel = new ConfigModel();
            $MessageModel = new MessageModel();
            $taskData = [
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'name' => $param['name'],
                'rating_scale_count' => count($param['rating_scale']),
                'time' => time()
            ];
            switch ($param['code_type']){
                case 1:
                    //个人
                    $this->validate($param,[
                        'uid|用户' => 'require'
                    ]);
                    $taskData['user_count'] = count($param['uid']);
                    foreach ($param['rating_scale'] as $item) {
                        $factor = $item['factor'] ?? [];
                        $factor_id_column = array_column($factor, 'factor_id');
                        if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                        foreach ($factor as $value) {
                            if ($item['id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                            $continuousData[] = [
                                'rating_scale_id' => $item['id'],
                                'factor_id' => $value['factor_id'],
                                'continuity_rating_scale_id' => $value['rating_scale_id'],
                                'time' => $taskData['time']
                            ];
                        }
                        //任务量表
                        $task_rating_scale[] = [
                            'rating_scale_id' => $item['id'],
                            'pack_id' => $item['pack_id'],
                            'time' => $taskData['time']
                        ];
                        //任务用户
                        foreach ($param['uid'] as $uid) {
                            $task_user[] = [
                                'rating_scale_id' => $item['id'],
                                'uid' => $uid,
                                'time' => $taskData['time']
                            ];
                            $MessageData[] = [
                                'uid' => $uid,
                                'type' => 3,
                                'title' => '发布任务',
                                'content' => $this->userData['name'] . '管理员发布了' . $taskData['name'] . '任务，请及时查看并完成测评任务。',
                                'time' => $taskData['time']
                            ];
                        }
                    }
                    break;
                case 2:
                    //部门
                    $this->validate($param,[
                        'department_id|部门' => 'require'
                    ]);
                    $UserModel = new UserModel();
                    $uid = $UserModel->where('department_id','=',$param['department_id'])->column('id');
                    $taskData['user_count'] = count($uid);
                    foreach ($param['rating_scale'] as $item) {
                        //预警连续测评
                        $factor = $item['factor'] ?? [];
                        $factor_id_column = array_column($factor, 'factor_id');
                        if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                        foreach ($factor as $value) {
                            if ($item['rating_scale_id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                            $continuousData[] = [
                                'rating_scale_id' => $item['rating_scale_id'],
                                'factor_id' => $value['factor_id'],
                                'continuity_rating_scale_id' => $value['rating_scale_id'],
                                'time' => $taskData['time']
                            ];
                        }
                        //任务量表
                        $task_rating_scale[] = [
                            'rating_scale_id' => $item['id'],
                            'pack_id' => $item['pack_id'],
                            'time' => $taskData['time']
                        ];
                        if (!empty($uid)){
                            foreach ($uid as $v) {
                                $task_user[] = [
                                    'rating_scale_id' => $item['rating_scale_id'],
                                    'uid' => $v,
                                    'time' => $taskData['time']
                                ];
                                $MessageData[] = [
                                    'uid' => $uid,
                                    'type' => 3,
                                    'title' => '发布任务',
                                    'content' => $this->userData['name'] . '管理员发布了' . $taskData['name'] . '任务，请及时查看并完成测评任务。',
                                    'time' => $taskData['time']
                                ];
                            }
                        }
                    }
                    break;
                default:
                    throw new \Exception('参数错误！');
            }
            if (!empty($taskData['is_time']) && $taskData['is_time'] == 1) {
                if (empty($taskData['start_time']) || empty($taskData['end_time'])) throw new \Exception('请填写开始和结束时间！');
                if ($taskData['start_time'] <= $taskData['time'] && $taskData['end_time'] >= $taskData['time']) {
                    //在任务时间内将任务设为进行中
                    $taskData['status'] = 2;
                }
            } else {
                $taskData['status'] = 2;
            }
            if (!empty($taskData['result_read_auth'])) {
                $taskData['result_read_auth'] = implode(',', $taskData['result_read_auth']);
            }
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'evaluation_task'
            ])->value('value') ?? '';
            $config = json_decode($data, true);
            if (isset($config['is_continuous'])) {
                $taskData['is_continuous'] = $config['is_continuous'] ? 1 : 0;
            }
            $taskData['is_redo'] = $config['is_redo'] ?? 0;
            $taskData['is_temporary'] = $config['is_temporary'] ?? 0;
            $task_id = $this->mode->insertGetId($taskData);
            if (!empty($continuousData)) {
                foreach ($continuousData as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskContinuousEvaluation->insertAll($continuousData);
            }
            if (!empty($task_user)) {
                foreach ($task_user as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskUserModel->insertAll($task_user, 200);
            }
            if (!empty($task_rating_scale)) {
                foreach ($task_rating_scale as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            $MessageData[] = [
                'uid' => $this->userData['id'],
                'type' => 3,
                'title' => '发布任务',
                'content' => '您于' . date('Y-m-d') . '日期' . date('H:i:s') . '时间发布的' . $taskData['name'] . '测评任务,已全部向用户推送完成。',
                'time' => time()
            ];
            $MessageModel->insertAll($MessageData, 200);
            $this->mode->commit();
            return success([], '添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑未开始任务（高校）
     * @return false|string
     */
    public function updateTask2(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'name|任务名称' => 'require',
                'type|量表类型' => 'require',
                'is_time|是否限时' => 'require',
                'rating_scale|量表' => 'require',
                'code_type|任务类型' => 'require'
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info->status != 1) throw new \Exception('未开始的任务才能编辑全部信息！');
            $info->save([
                'is_del' => 1,
                'del_time' => time(),
            ]);
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskUserModel = new TaskUserModel();
            $TaskContinuousEvaluation = new TaskContinuousEvaluationModel();
            $ConfigModel = new ConfigModel();
            $MessageModel = new MessageModel();
            $taskData = [
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'name' => $param['name'],
                'rating_scale_count' => count($param['rating_scale']),
                'time' => time()
            ];
            switch ($param['code_type']){
                case 1:
                    //个人
                    $this->validate($param,[
                        'uid|用户' => 'require'
                    ]);
                    $taskData['user_count'] = count($param['uid']);
                    foreach ($param['rating_scale'] as $item) {
                        $factor = $item['factor'] ?? [];
                        $factor_id_column = array_column($factor, 'factor_id');
                        if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                        foreach ($factor as $value) {
                            if ($item['id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                            $continuousData[] = [
                                'rating_scale_id' => $item['id'],
                                'factor_id' => $value['factor_id'],
                                'continuity_rating_scale_id' => $value['rating_scale_id'],
                                'time' => $taskData['time']
                            ];
                        }
                        //任务量表
                        $task_rating_scale[] = [
                            'rating_scale_id' => $item['id'],
                            'pack_id' => $item['pack_id'],
                            'time' => $taskData['time']
                        ];
                        //任务用户
                        foreach ($param['uid'] as $uid) {
                            $task_user[] = [
                                'rating_scale_id' => $item['id'],
                                'uid' => $uid,
                                'time' => $taskData['time']
                            ];
                            $MessageData[] = [
                                'uid' => $uid,
                                'type' => 3,
                                'title' => '发布任务',
                                'content' => $this->userData['name'] . '管理员发布了' . $taskData['name'] . '任务，请及时查看并完成测评任务。',
                                'time' => $taskData['time']
                            ];
                        }
                    }
                    break;
                case 2:
                    //部门
                    $this->validate($param,[
                        'department_id|部门' => 'require'
                    ]);
                    $UserModel = new UserModel();
                    $uid = $UserModel->where('department_id','=',$param['department_id'])->column('id');
                    $taskData['user_count'] = count($uid);
                    foreach ($param['rating_scale'] as $item) {
                        //预警连续测评
                        $factor = $item['factor'] ?? [];
                        $factor_id_column = array_column($factor, 'factor_id');
                        if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                        foreach ($factor as $value) {
                            if ($item['rating_scale_id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                            $continuousData[] = [
                                'rating_scale_id' => $item['rating_scale_id'],
                                'factor_id' => $value['factor_id'],
                                'continuity_rating_scale_id' => $value['rating_scale_id'],
                                'time' => $taskData['time']
                            ];
                        }
                        //任务量表
                        $task_rating_scale[] = [
                            'rating_scale_id' => $item['id'],
                            'pack_id' => $item['pack_id'],
                            'time' => $taskData['time']
                        ];
                        if (!empty($uid)){
                            foreach ($uid as $v) {
                                $task_user[] = [
                                    'rating_scale_id' => $item['rating_scale_id'],
                                    'uid' => $v,
                                    'time' => $taskData['time']
                                ];
                                $MessageData[] = [
                                    'uid' => $uid,
                                    'type' => 3,
                                    'title' => '发布任务',
                                    'content' => $this->userData['name'] . '管理员发布了' . $taskData['name'] . '任务，请及时查看并完成测评任务。',
                                    'time' => $taskData['time']
                                ];
                            }
                        }
                    }
                    break;
                default:
                    throw new \Exception('参数错误！');
            }
            if (!empty($taskData['is_time']) && $taskData['is_time'] == 1) {
                if (empty($taskData['start_time']) || empty($taskData['end_time'])) throw new \Exception('请填写开始和结束时间！');
                if ($taskData['start_time'] <= $taskData['time'] && $taskData['end_time'] >= $taskData['time']) {
                    //在任务时间内将任务设为进行中
                    $taskData['status'] = 2;
                }
            } else {
                $taskData['status'] = 2;
            }
            if (!empty($taskData['result_read_auth'])) {
                $taskData['result_read_auth'] = implode(',', $taskData['result_read_auth']);
            }
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'evaluation_task'
            ])->value('value') ?? '';
            $config = json_decode($data, true);
            if (isset($config['is_continuous'])) {
                $taskData['is_continuous'] = $config['is_continuous'] ? 1 : 0;
            }
            $taskData['is_redo'] = $config['is_redo'] ?? 0;
            $taskData['is_temporary'] = $config['is_temporary'] ?? 0;
            $task_id = $this->mode->insertGetId($taskData);
            if (!empty($continuousData)) {
                foreach ($continuousData as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskContinuousEvaluation->insertAll($continuousData);
            }
            if (!empty($task_user)) {
                foreach ($task_user as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskUserModel->insertAll($task_user, 200);
            }
            if (!empty($task_rating_scale)) {
                foreach ($task_rating_scale as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            $MessageData[] = [
                'uid' => $this->userData['id'],
                'type' => 3,
                'title' => '发布任务',
                'content' => '您于' . date('Y-m-d') . '日期' . date('H:i:s') . '时间发布的' . $taskData['name'] . '测评任务,已全部向用户推送完成。',
                'time' => time()
            ];
            $MessageModel->insertAll($MessageData, 200);
            $this->mode->commit();
            return success([], '添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑已开始任务（高校）
     * @return false|string
     */
    public function updateTask3(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'is_time|是否限时' => 'require',
            ]);
            if ($param['is_time'] == 1) {
                if (empty($param['end_time'])) throw new \Exception('请填写开始和结束时间！');
                $time = time();
                if ($param['start_time']??0 <= $time && $param['end_time'] > $time) {
                    //在任务时间内将任务设为进行中
                    $param['status'] = 2;
                }
            } else {
                $param['status'] = 2;
            }
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['result_read_auth'])) {
                $param['result_read_auth'] = implode(',', $param['result_read_auth']);
            }
            $info->save($param);
            return success([], '添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}
